Blog

03/06/2019

sed Tip: Delete All Blank White Spaces



I have a text file as follows:

   foo
   bar
  foobar 

How can I delete all leading and/or trailing blank spaces, tab from each line using sed command?

You can use sed command to delete all white (blank) spaces in a text file. You can also use other text processing utilities such as:

  1. Perl.
  2. Python.
  3. Awk and friends.

Perl example

The syntax is:

perl -lape 's/s+//sg' input > output

Sample outputs:

foo
bar
foobar

Or use -pie syntax to update file:

cat input
perl -lapi -e 's/s+|^n//sg'  input
cat input

See perl man page for more information.

Sed example

The syntax is:

sed -e 's/^[ t]*//' -e 's/[ t]*$//' input > output

OR updated file in a single go with the -i option:

sed -i -e 's/^[ t]*//' -e 's/[ t]*$//' input

See sed command man page for more information.

Awk example

The syntax is

awk '{$1=$1}{ print }' input > output

You can also use gsub() substring matching the regular expression function. See awk man page for more information.

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...