Losing newline after assigning grep result to a sh

2020-01-26 04:50发布

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

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?

标签: shell
3条回答
劳资没心,怎么记你
2楼-- · 2020-01-26 05:19

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 "====="

which outputs:

=====
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)
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-01-26 05:19

Put $out in quotes:

#!/usr/local/bin/bash
out=`grep apache README`
echo "$out";
查看更多
爷、活的狠高调
4楼-- · 2020-01-26 05:34

Quoting variables in bash preserves the whitespace.

For instance:

#!/bin/bash
var1="A B  C   D"
echo $var1   # A B C D
echo "$var1" # A B  C   D

since newlines are whitespace they get "removed"

查看更多
登录 后发表回答