How do I trim lines read from standard input on bash?

donatello picture donatello · Dec 12, 2010 · Viewed 30.9k times · Source

I want a bash way to read lines from standard input (so I can pipe input to it), and remove just the leading and trailing space characters. Piping to echo does not work.

For example, if the input is:

     12 s3c  
     sd wqr

the output should be:

12 s3c
sd wqr

I want to avoid writing a python script or similar for something as trivial as this. Any help is appreciated!

Answer

phillip picture phillip · Dec 12, 2010

You can use sed to trim it.

sed 's/^ *//;s/ *$//'

You can test it really easily on a command line by doing:

echo -n "  12 s3c  " | sed 's/^ *//;s/ *$//' && echo c