如何用换行符保存grep结果? [英] How to preserve grep result with newline?

查看:46
本文介绍了如何用换行符保存grep结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将grep结果分配给变量以供进一步使用:

I want to assign grep result to a variable for further use:

lines=`cat abc.txt | grep "hello"`

但是我发现的是$ lines不再包含换行符.所以当我这样做

but what i found is $lines doesn't contain newline character anymore. So when I do

echo $lines

仅打印一行.我如何保留换行符,所以当我回显$ lines时,它与cat abc.txt |grep你好".

only one line is printed. How can i preserve newline character, so when i echo $lines, it's just the same as cat abc.txt | grep "hello".

推荐答案

你想说

echo "$lines"

代替

echo $lines

详细说明:

echo $ lines 的意思是用名为 lines 的变量内容替换 $ lines ,形成一个新命令,将其拆分为空格以形成 echo 命令的零个或多个新参数,例如:

echo $lines means "Form a new command by replacing $lines with the contents of the variable named lines, splitting it up on whitespace to form zero or more new arguments to the echo command. For example:

lines='1 2 3'
echo $lines   # equivalent to "echo 1 2 3"
lines='1   2   3'
echo $lines   # also equivalent to "echo 1 2 3"
lines="1
2
3"
echo $lines   # also equivalent to "echo 1 2 3"

所有这些示例都是等效的,因为外壳程序忽略了存储在变量 lines 中的各个单词之间的特定类型的空格.实际上,更确切地说,外壳程序将特殊的 IFS (内部字段分隔符)字符的变量内容拆分为默认值(至少在我的bash版本中)为三个字符空格,制表符和换行符.

All these examples are equivalent, because the shell ignores the specific kind of whitespace between the individual words stored in the variable lines. Actually, to be more precise, the shell splits the contents of the variable on the characters of the special IFS (Internal Field Separator) variable, which defaults (at least on my version of bash) to the three characters space, tab, and newline.

echo"$ lines" 意味着根据变量 lines 的确切值形成一个新的自变量.

echo "$lines", on the other hand, means to form a single new argument from the exact value of the variable lines.

有关更多详细信息,请参见bash手册页的扩展"和单词拆分"部分.

For more details, see the "Expansion" and "Word Splitting" sections of the bash manual page.

这篇关于如何用换行符保存grep结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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