How can I write grep pattern in multiple lines, inside bash script? Like that:

grep -o -P '
' input.txt

When I wrote php programs, I could do so. Now tried this in the bash script - it doesn't work. It is very unhandy write all in one line :(

May be exist option, which allows formatting inside pattern, that is, grep doesn't notice whitespaces (spaces and newlines), when this option is enabled.

grep version:

grep -V
grep (GNU grep) 2.25

grep takes newlines as separating different patterns. But you could save the pattern in a variable, and then remove the whitespace before passing it to grep:

$ ws=$' \t\n'
$ pat=$'a b\nc'
$ echo abcd | grep "${pat//[$'\n\t ']}"

(Didn't test with anything more complex.)


Even with -P which enables (?x:) you can't ignore newlines. For spaces and tabs, it works:

echo abab | grep -P $'(?x:a b a\tb)'

But newline doesn't work the same way:

echo ab | grep -P $'(?x:a\nb)'
grep: the -P option only supports a single pattern

At least in GNU grep 2.16.

  • Isn't that a bug? It seems distinctly not perl-compatible. – bukzor Jul 28 '18 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.