Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

trim

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!

like image 777
donatello Avatar asked Dec 12 '10 15:12

donatello


People also ask

How do I trim a line in bash?

You can use sed to trim it. And \s instead of space in a case of TABs. So, here's what I found: sed -r 's/\s*(. *)\s*/\1/' will mostly work, but I think it will not trim the end of the line, since the .

How do I turn off standard input shell?

The simple, non-technical, answer is that Ctrl + D terminates the STDIN file and that Ctrl + C terminates the active application. Both are handled in the keyboard driver and apply to all programs reading from the keyboard. To see the difference start a command line shell and enter the wc command with no arguments.

How do I skip a line in a bash script?

Using head to get the first lines of a stream, and tail to get the last lines in a stream is intuitive. But if you need to skip the first few lines of a stream, then you use tail “-n +k” syntax. And to skip the last lines of a stream head “-n -k” syntax.


1 Answers

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 
like image 182
phillip Avatar answered Sep 18 '22 23:09

phillip