开发者

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!


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


$ trim () { read -r line; echo "$line"; }
$ echo "   aa   bb   cc   " | trim
aa   bb   cc
$ a=$(echo "   aa   bb   cc   " | trim)
$ echo "..$a.."
..aa   bb   cc..

To make it work for multi-line input, just add a while loop:

trim () { while read -r line; do echo "$line"; done; }

Using sed with only one substitution:

sed 's/^\s*\(.*[^ \t]\)\(\s\+\)*$/\1/'


Add this:
| sed -r 's/\s*(.*?)\s*$/\1/'


your_command | xargs -L1 echo

This works because echo converts all tabls to spaces and then all multiple spaces to a single space, not only leading and trailing, see example:

$ printf "  1\t\t\t2    3"
  1         2    3
$ echo `printf "  1\t\t\t2    3"`
1 2 3

The drawback is that it will also remove some useful characters like \ ' ".


I know this is old, but there is another simple and dirty way:

line=$(echo $line)

See this example:

user@host:~$ x="    abc  "
user@host:~$ echo "+$x+"
+    abc  +
user@host:~$ y=$(echo $x)
user@host:~$ echo "$y"
+abc+


grep -o -E '\S.*\S|\S'

Еxplanation:

  • - print only matches
  • -E - use extended regular expression syntax
  • '\S.*\S':
    • match the first non-space symbol, then greedy match any number of any symbols, then match a non-space symbol
    • or, if the first part is not matched (i.e. there are no two non-space symbols), match a single non-space symbol
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜