6

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?

1
  • 1
    Are you sure that the newlines are not preserved when assigning the text to the variable? Are you saying echo $r or echo "$r"? If you're saying echo $r, then the newlines are getting stripped on output. Oct 9, 2014 at 23:31

1 Answer 1

9

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)

1
  • I'm outputing the $r to a 'hits.txt' file. Ah yes, "$r" made the difference. Thanks!
    – pfmasse60
    Oct 9, 2014 at 23:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .