Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use sed to delete all leading/following blank spaces in a text file

Tags:

linux

text

unix

sed

File1:

  hello  
  world  

How would one delete the leading/trailing blank spaces within this file using sed - using one command (no intermediate files)?

I've currently got:

sed -e 's/^[ \t]*//' a > b

For leading spaces.

sed 's/ *$//' b > c

And this for trailing spaces.

like image 617
user191960 Avatar asked Oct 20 '09 08:10

user191960


2 Answers

You almost got it:

sed -e 's/^[ \t]*//;s/[ \t]*$//' a > c

Moreover on some flavours of sed, there is also an option for editing inline:

sed -i -e 's/^[ \t]*//;s/[ \t]*$//' a
like image 178
mouviciel Avatar answered Oct 16 '22 08:10

mouviciel


easier way, using awk

awk '{$1=$1}1' file

or

awk '{gsub(/^ +|  +$/,"")}1' file
like image 32
ghostdog74 Avatar answered Oct 16 '22 08:10

ghostdog74