Preserving newline in find/grep search results

bashfindgrepnewlines

I am recursively searching for the occurrence of php scripts being called from other files using the following script.

find . -exec grep -Hn $1 {} \; | grep -v ^Binary;

Works great! Now, I need the returned results to determine the action to be taken next.

r=$(find . -exec grep -Hn $str {} \; | grep -v ^Binary;)

 if [ -z "$r" ];
    then
          Do this
    else
          Do something else
    fi

PROBLEM: By it's self the find script returns the results, each on a new line.

./path/to/file.php
./path/to/another_file.php
./path/to/third_file.php

However, when assigning the output to the $r variable, the newline character is not preserved and the results are printed on one line making it difficult to read.

./path/to/file.php ./path/to/file.php ./path/to/third_file.php

How do I preserve the newline character while assigning the output into a variable?

Best Answer

You don't show what you do with $r, but I bet it's

echo $r

You need to enclose the variable in double quotes to preserve the newlines

echo "$r"

Unquoted, the variable is subject to word splitting, where any sequences of whitespace 1 (including newlines) are replaced by a single space 1

1: by default, depends on the contents of $IFS (default: space, tab, newline)

Related Question