sed Tip: Delete All Blank White Spaces

I have a text file as follows:




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:



Awk and friends.

Perl example

The syntax is:

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

Sample outputs:




Or use -pie syntax to update file:

cat input

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

cat input

See perl(1) 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(1) 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(1) for more information.



Leave a Reply

Your email address will not be published. Required fields are marked *