I want to assign the grep result to a variable for further use:
lines=$(cat abc.txt | grep "hello")
but what I found wa $lines
doesn't contain newline characters. So when I do
echo $lines
only one line is printed. How can I preserve newline characters, so when I echo $lines, it generates the same result as cat abc.txt | grep "hello"
.
You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.
If there's no match, that should generally be considered a failure, so a return of 0 would not be appropriate. Indeed, grep returns 0 if it matches, and non-zero if it does not.
The grep command searches a text file based on a series of options and search string and returns the lines of the text file which contain the matching search string.
You want to say
echo "$lines"
instead of
echo $lines
To elaborate:
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"
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"
, on the other hand, means to form a single new argument from the exact value of the variable lines
.
For more details, see the "Expansion" and "Word Splitting" sections of the bash manual page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With