bash 如何用换行符保留grep结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5386502/
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 preserve grep result with newline?
提问by Dagang
I want to assign grep result to a variable for further use:
我想将 grep 结果分配给一个变量以供进一步使用:
lines=`cat abc.txt | grep "hello"`
but what i found is $lines doesn't contain newline character anymore. So when I do
但我发现 $lines 不再包含换行符。所以当我做
echo $lines
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".
只打印一行。我如何保留换行符,所以当我回显 $lines 时,它与 cat abc.txt | 相同 grep“你好”。
回答by Sean
You want to say
你想说
echo "$lines"
instead of
代替
echo $lines
To elaborate:
详细说明:
echo $linesmeans "Form a new command by replacing $lineswith the contents of the variable named lines, splitting it up on whitespace to form zero or more new arguments to the echocommand. For example:
echo $lines意思是“通过替换$lines名为 的变量的内容来形成一个新命令,lines在空白处将其拆分以形成echo命令的零个或多个新参数。例如:
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"
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.
所有这些示例都是等效的,因为 shell 会忽略存储在变量 中的各个单词之间的特定类型的空格lines。实际上,更准确地说,shell 根据特殊IFS(内部字段分隔符)变量的字符拆分变量的内容,该变量默认(至少在我的 bash 版本中)为空格、制表符和换行符这三个字符。
echo "$lines", on the other hand, means to form a single new argument from the exact value of the variable lines.
echo "$lines",另一方面,意味着从变量 的确切值形成一个新的参数lines。
For more details, see the "Expansion" and "Word Splitting" sections of the bash manual page.
有关更多详细信息,请参阅 bash 手册页的“扩展”和“分词”部分。
回答by Haggisbreath
Using the Windows port for grep (not the original question, I kow and not applicable to *nix). I found that -Usolved the problem nicely.
使用 Windows 端口进行 grep(不是原始问题,我知道并且不适用于 *nix)。我发现这-U很好地解决了这个问题。
From the --help:
来自--help:
-U, --binary do not strip CR characters at EOL (MSDOS)
-U, --binary 不要在 EOL (MSDOS) 删除 CR 字符

