Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get rid of "--" line separator when using grep with context lines?

Tags:

grep

I have a text file named compare.txt where I want to extract the single line that follows every line that contains the pattern nmse_gain_constant. The following command gets me close:

grep -A 1 nmse_gain_constant compare.txt | grep -v nmse_gain_constant 

But this includes a separator -- line between every line of desired text. Any easy ideas how to get rid of the -- lines?

Example: for an input file that looks like

line line nmse_gain_constant matching line line after first match line line nmse_gain_constant another matching line line after second match line nmse_gain_constant a third matching line line after third match 

the output is

line after first match -- line after second match -- line after third match 

but I'd like to have just

line after first match line after second match line after third match 
like image 714
Michael Avatar asked Jan 30 '10 13:01

Michael


People also ask

How do you grep with surrounding lines?

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.

What does the '- V option to grep do?

-v means "invert the match" in grep, in other words, return all non matching lines.

How do you get 5 lines before and after grep?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.


2 Answers

I do this:

 grep ... | grep -v -- "^--$" 

But this works too (on many, not all OS'es)!

grep --no-group-separator ... 

And it doesn't spit out that "--" or even a blank line.

like image 191
Erik Aronesty Avatar answered Sep 25 '22 00:09

Erik Aronesty


There is an undocumented parameter of grep: "--group-separator", which overrides the default "--". You can set it to "" to get rid of the double dash. Though, you still get an empty line. I had the same trouble, and found this param by reading the source code of grep.

like image 38
Shaohua Li Avatar answered Sep 24 '22 00:09

Shaohua Li