Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give a pattern for new line in grep?

Tags:

grep

bash

newline

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.

like image 510
tuxnani Avatar asked Sep 29 '12 12:09

tuxnani


People also ask

How do you grep a pattern?

To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.

How do you grep first occurrence?

-m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.


2 Answers

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.

like image 53
nullrevolution Avatar answered Sep 20 '22 15:09

nullrevolution


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  
like image 44
arash kordi Avatar answered Sep 20 '22 15:09

arash kordi