Linux 如何防止grep打印尾随换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7249755/
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
How to prevent grep from printing a trailing newline?
提问by Cobra_Fast
I am using grep
to produce output that will be parsed by another program.
我正在使用grep
生成将由另一个程序解析的输出。
However, that program expects output only to be numeric or zero-bytes.
但是,该程序只希望输出为数字或零字节。
Now grep
outputs a newline character after its output. I've checked the -Z
option but it doesn't seem to work as I'm using grep for counting (-c
).
现在在grep
输出后输出一个换行符。我已经检查了该-Z
选项,但它似乎不起作用,因为我正在使用 grep 进行计数 ( -c
)。
I am executing in sh
, not bash
. So nesting it into echo -n "$(grep -c pattern)"
doesn't work either.
我在 中执行sh
,而不是bash
。所以嵌套它echo -n "$(grep -c pattern)"
也不起作用。
How can I get rid off the trailing newline?
我怎样才能摆脱尾随的换行符?
采纳答案by Amardeep AC9MF
You can pipe it through tr
and translate the \n
to a \0
character:
您可以通过管道将其tr
转换\n
为\0
字符:
tr '\n' '$ grep -c ' ' /etc/passwd | tr -d '\n'
69$ grep -c ' ' /etc/passwd | tr -d '\n' | xxd
0000000: 3639 69
$
'
回答by user.friendly
I know this is old, and tr works just as well, but I happened across this question and noticed OP stated: I am executing in sh, not bash. So nesting it into echo -n "$(grep -c pattern)" doesn't work either.
我知道这是旧的,并且 tr 也能正常工作,但是我遇到了这个问题并注意到 OP 声明: 我在 sh 中执行,而不是 bash。所以将它嵌套到 echo -n "$(grep -c pattern)" 中也不起作用。
This isn't grep or sh so much as how echo is being used. For future visitors, the only reason this didn't work is due to the double quotes around the substituted command. The following does, in fact, work even using sh.
与使用 echo 的方式不同,这与 grep 或 sh 不同。对于未来的访问者,这不起作用的唯一原因是替换命令周围的双引号。事实上,即使使用 sh,以下内容也能正常工作。
$ ls /dev/sd? #example of formatted output
/dev/sda /dev/sdc /dev/sde /dev/sdg /dev/sdi /dev/sdk
/dev/sdb /dev/sdd /dev/sdf /dev/sdh /dev/sdj
$ echo $(ls /dev/sd?) #without -n, appends \n only at the end
/dev/sda /dev/sdb /dev/sdc /dev/sdd /dev/sde /dev/sdf /dev/sdg /dev/sdh /dev/sdi /dev/sdj /dev/sdk
$ echo -n $(ls /dev/sd?) #with -n, does not append the \n, but still strips the line breaks from the string
/dev/sda /dev/sdb /dev/sdc /dev/sdd /dev/sde /dev/sdf /dev/sdg /dev/sdh /dev/sdi /dev/sdj /dev/sdk
$ echo -n "$(ls /dev/sd?)" #output when double quotes are used
/dev/sda
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf
/dev/sdg
/dev/sdh
/dev/sdi
/dev/sdj
/dev/sdk
Examples:
例子:
##代码##