16

I want to check if a multiline text matches an input. grep comes close, but I couldn't find a way to make it interpret pattern as plain text, not regex.

How can I do this, using only Unix utilities?

0

3 Answers 3

17

Use grep -F:

-F, --fixed-strings

Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified by POSIX.)

EDIT: Initially I didn't understand the question well enough. If the pattern itself contains newlines, use -z option:

   -z, --null-data
          Treat  the  input  as  a set of lines, each terminated by a zero
          byte (the ASCII NUL character) instead of a newline.   Like  the
          -Z  or --null option, this option can be used with commands like
          sort -z to process arbitrary file names.

I've tested it, multiline patterns worked.

Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work on ubuntu: With echo '->' | grep -F '->' . I get Usage: grep [OPTION]... PATTERN [FILE]...
1

From man grep

-F, --fixed-strings
       Interpret  PATTERN  as  a  list  of  fixed strings, separated by
       newlines, any of which is to be matched.  (-F  is  specified  by
       POSIX.)

1 Comment

Unless I'm missing something, I don't think I can match multiline input with this. For example, match "a\nb" in a file with "z\na\nb\nc"?
1

If the input string you are trying to match does not contain a blank line (eg, it does not have two consecutive newlines), you can do:

awk 'index( $0, "needle\nwith no consecutive newlines" ) { m=1 }
    END{ exit !m }' RS= input-file && echo matched

If you need to find a string with consecutive newlines, set RS to some string that is not in the file. (Note that the results of awk are unspecified if you set RS to more than one character, but most awk will allow it to be a string.) If you are willing to make the sought string a regex, and if your awk supports setting RS to more than one character, you could do:

awk 'END{ exit NR == 1 }' RS='sought regex' input-file && echo matched

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.