Search code examples
awkgrepmultilinestring

Check for multi-line content in a file


I'm trying to check if a multi-line string exists in a file using common bash commands (grep, awk, ...).

I want to have a file with a few lines, plain lines, not patterns, that should exists in another file and create a command (sequence) that checks if it does. If grep could accept arbitrary multiline patterns, I'd do it with something similar to

grep "`cat contentfile`" targetfile

As with grep I'd like to be able to check the exit code from the command. I'm not really interested in the output. Actually no output would be preferred since then I don't have to pipe to /dev/null.

I've searched for hints, but can't come up with a search that gives any good hits. There's How can I search for a multiline pattern in a file?, but that is about pattern matching.

I've found pcre2grep, but need to use "standard" *nix tools.

Example:

contentfile:

line 3
line 4
line 5

targetfile:

line 1
line 2
line 3
line 4
line 5
line 6

This should match and return 0 since the sequence of lines in the content file is found (in the exact same order) in the target file.

EDIT: Sorry for not being clear about the "pattern" vs. "string" comparison and the "output" vs. "exit code" in the previous versions of this question.


Solution

  • Following up on a comment from Cyrus, who pointed to How to know if a text file is a subset of another, the following Python one-liner does the trick

    python -c "content=open('content').read(); target=open('target').read(); exit(0 if content in target else 1);"