How to give a pattern for new line in grep?

BashGrepNewline

Bash Problem Overview


How to give a pattern for new line in grep? New line at beginning, new line at end. Not the regular expression way. Something like \n.

Bash Solutions


Solution 1 - Bash

try pcregrep instead of regular grep:

pcregrep -M "pattern1.*\n.*pattern2" filename

the -M option allows it to match across multiple lines, so you can search for newlines as \n.

Solution 2 - Bash

grep patterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.

However you can find empty lines like this:

grep '^$' file
grep '^[[:space:]]*$' file # include white spaces 

Solution 3 - Bash

Thanks to @jarno I know about the -z option and I found out that when using GNU grep with the -P option, matching against \n is possible. :)

Example:

grep -zoP 'foo\n\K.*'<<<$'foo\nbar'

Result:

bar

Example that involves matching everything including newlines:

.* will not match newlines. To match everything including newlines, use1 (.|\n)*:

grep -zoP 'foo\n\K(.|\n)*'<<<$'foo\nbar\nqux'

Result:

bar
qux

1 Seen here: https://stackoverflow.com/a/33418344

Solution 4 - Bash

You can use this way...

grep -P '^\s$' file
  • -P is used for Perl regular expressions (an extension to POSIX grep).
  • \s match the white space characters; if followed by *, it matches an empty line also.
  • ^ matches the beginning of the line. $ matches the end of the line.

Solution 5 - Bash

As for the workaround (without using non-portable -P), you can temporary replace a new-line character with the different one and change it back, e.g.:

grep -o "_foo_" <(paste -sd_ file) | tr -d '_'

Basically it's looking for exact match _foo_ where _ means \n (so __ = \n\n). You don't have to translate it back by tr '_' '\n', as each pattern would be printed in the new line anyway, so removing _ is enough.

Solution 6 - Bash

just found

grep $'\r'

It's using $'\r' for c-style escape in Bash.

in this article

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontuxnaniView Question on Stackoverflow
Solution 1 - BashnullrevolutionView Answer on Stackoverflow
Solution 2 - Basharash kordiView Answer on Stackoverflow
Solution 3 - BashrubystallionView Answer on Stackoverflow
Solution 4 - BashManikandan RajendranView Answer on Stackoverflow
Solution 5 - BashkenorbView Answer on Stackoverflow
Solution 6 - BashHHHartmannView Answer on Stackoverflow