Search code examples
bashtrim

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


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!


Solution

  • 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