How can grep treat escaped newlines as real newlines?

I'm using grep to find a word in some directory:

grep -r my_word directory

In this directory there are files containing my_word with escaped newlines (\n) so the output from grep is similar to:

file_name.txt:first line\n second line my_word\n third line

How can I force grep to treat \n as new lines and show something like:

second line my_word

Upvotes: 0

Views: 31

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52431

You could pipe the result through sed to convert the newlines, then grep again:

grep -r my_word directory | sed 's/\\n/\n/g' | grep 'my_word'

Alternatively, if your grep supports Perl compatible regular expressions (such as GNU grep), you can use look-arounds:

$ grep -Po '.*^|\\n\K.*my_word.*?(?=\\n|$)' myfile
 second line my_word

This uses a variable-length look-behind, .*^|\\n\K, to greedily remove everything up to the last occurrence of \n before the line with your search term, and .*?(?=\\n|$) non-greedily matches the rest of the line until the next \n (or end of line).

If you don't want the filename in your result in case the match is in the first "subline", you can suppress the filenames with grep -h.

Upvotes: 1

Related Questions