Reputation: 165
I'm using grep to search a pattern through a file contained in a var
Code here:
result=`grep "$pattern" $file`
echo $result
Result: A) somewords B)somelines C)somenumbers
print result on 1 line. I would like to have results one for line a
Like:
A) somewords
B) somelines
C) somenumbers
How can I?
Thanks
Upvotes: 1
Views: 478
Reputation: 11786
Just quote your $result
variable and the newlines will be preserved:
result=$(grep "$pattern" $file)
echo "$result"
The reason this works is that when you enclose something in double quotes in bash, everything inside those quotes is treated as a single word. This means that it won't be subject to word splitting. See also: http://mywiki.wooledge.org/WordSplitting
Effectively when you use $result
, it gets expanded to this (because the newlines are treated as delimiters):
echo A) somewords B) somelines C) somenumbers
When you use "$result"
and avoid the word splitting, it gets expanded to this:
echo "A) somewords
B) somelines
C) somenumbers"
Additional note: using $(...)
instead of backticks improves readability and also is more portable.
Upvotes: 2