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

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

How to prevent grep from printing a trailing newline?

linuxgrepnewline

提问by Cobra_Fast

I am using grepto produce output that will be parsed by another program.

我正在使用grep生成将由另一个程序解析的输出。

However, that program expects output only to be numeric or zero-bytes.

但是,该程序只希望输出为数字或零字节。

Now grepoutputs a newline character after its output. I've checked the -Zoption 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 trand translate the \nto a \0character:

您可以通过管道将其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 Johnsyweb

Use tr -dto delete characters in a string:

使用tr -d到的字符串删除字符:

echo -n $(grep -c pattern)

回答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:

例子:

##代码##