Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save both matching and non-matching from grep

I use grep very often and am familiar with it's ability to return matching lines (by default) and non-matching lines (using the -v parameter). However, I want to be able to grep a file once to separate matching and non-matching lines.

If this is not possible, please let me know. I realize I could do this easily in perl or awk, but am curious if it is possible with grep.

Thanks!

like image 849
jake9115 Avatar asked Apr 03 '13 13:04

jake9115


People also ask

How do you grep for lines that don't match?

To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters). By default, grep is case-sensitive.

How do you print only the matched pattern using grep?

Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option. 6. Show line number while displaying the output using grep -n : To show the line number of file with the line matched.

How do I print two lines after grep match?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after. Save this answer.


2 Answers

If it does NOT have to be grep - this is a single pass split based on a pattern -- pattern found > file1 pattern not found > file2

awk '/pattern/ {print $0 > "file1"; next}{print $0 > "file2"}' inputfile
like image 167
jim mcnamara Avatar answered Sep 22 '22 10:09

jim mcnamara


I had the exact same problem and I wrote a small Perl script for that [1]. It only accepts one argument: the regex to grep input on.

[1] https://gist.github.com/tonejito/c9c0bffd75d8c81483f9107c609439e1

It reads STDIN by line and checks against the given regex, matched lines go to STDOUT and not matched go to STDERR.

I made it this way because this tool sits in the middle of a pipeline and I use shell redirection to save the files on their final location.

like image 23
tonejito Avatar answered Sep 19 '22 10:09

tonejito