将 grep 结果分配给 shell 变量后丢失换行符 [英] Losing newline after assigning grep result to a shell variable

查看:90
本文介绍了将 grep 结果分配给 shell 变量后丢失换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/local/bin/bash
out=`grep apache README`
echo $out;

在命令行上运行时,通常 grep 在单独的行中显示每个匹配项.但是,在上述脚本中,分隔每个匹配项的换行符消失了.有谁知道如何保留换行符?

Usually grep shows each match on a separate line when run on the command line. However, in the above scripts, the newline separating each match disappears. Does anyone know how the newline can be preserved?

推荐答案

你不是在作业中丢失了它,而是在回声中丢失了它.如果您:

You're not losing it in the assignment but in the echo. You can see this clearly if you:

echo "${out}"

您将在以下脚本中看到类似的效果:

You'll see a similar effect with the following script:

x="Hello,
I
am
a
string
with
newlines"
echo "====="
echo ${x}
echo "====="
echo "${x}"
echo "====="

输出:

=====
Hello, I am a string with newlines
=====
Hello,
I
am
a
string
with
newlines
=====

而且,与您的问题无关,但无论如何我想提一下,我更喜欢使用 $() 构造而不是反引号,只是为了能够嵌套命令的额外好处.所以你的脚本行变成:

And, irrelevant to your question but I'd like to mention it anyway, I prefer to use the $() construct rather than backticks, just for the added benefit of being able to nest commands. So your script line becomes:

out=$(grep apache README)

现在看起来可能没有什么不同(事实上也没有),但它使更复杂的命令成为可能,例如:

Now that may not look any different (and it isn't) but it makes possible more complex commands like:

lines_with_nine=$(grep $(expr 7 + 2) inputfile)

这篇关于将 grep 结果分配给 shell 变量后丢失换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆