Lars Nyström Lars Nyström - 3 months ago 10
Bash Question

How do I test if a file contains a specific, multiline, literal string?

I would like to grep for a literal string which contains newlines. I found this question but the accepted answer suggests the

-F
option, which uses a set of newline-separated strings. I also found this question which uses
pcregrep
with the
-M
option, but that matches regexes and not just literal strings.

So how can I test if a file contains a specific, multiline, literal string?

Answer

Here's one way you could do it using awk:

awk -v str="$string" 'BEGIN { n = split(str, lines, /\n/); i = 1 } 
    lines[i] == $0 { if (i++ == n) print "matched"; next } { i = 1 }' file

Split the string into an array of lines. n is the total number of lines (returned by split) and i keeps track of the current line to compare.

If the current line matches and we have reached the last line, print the message and skip to the next line. Otherwise, reset the line counter back to 1.

Comments