Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve newline characters in grep result?

Tags:

bash

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

like image 524
Dagang Avatar asked Mar 22 '11 03:03

Dagang


People also ask

How do I grep next 10 lines?

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.

What does grep return if no match?

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.

Does grep return a string?

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.


1 Answers

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.

like image 104
Sean Avatar answered Sep 25 '22 07:09

Sean