如何修剪从 bash 标准输入读取的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4422491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:57:09  来源:igfitidea点击:

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

bashtrim

提问by donatello

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.

我想要一种从标准输入读取行的 bash 方式(这样我就可以将输入通过管道传输到它),并只删除前导和尾随空格字符。管道回声不起作用。

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!

我想避免为像这样微不足道的事情编写 python 脚本或类似的脚本。任何帮助表示赞赏!

回答by phillip

You can use sed to trim it.

您可以使用 sed 来修剪它。

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

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

您可以通过执行以下操作在命令行上轻松测试它:

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

回答by Paused until further notice.

$ 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 whileloop:

要使其适用于多行输入,只需添加一个while循环:

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

Using sedwith only onesubstitution:

sed仅使用一种替换:

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

回答by Nakilon

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

添加这个:
| sed -r 's/\s*(.*?)\s*$/\1/'

回答by Akira

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+

回答by exebook

your_command | xargs -L1 echo

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

这是有效的,因为echo将所有 tabls 转换为空格,然后将所有多个空格转换为单个空格,而不仅仅是前导和尾随,请参见示例:

$ 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 \'".

缺点是它还会删除一些有用的字符,例如\'".