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

Grep

Grep Problem Overview


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

Grep Solutions


Solution 1 - Grep

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.

Solution 2 - Grep

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.

Solution 3 - Grep

Well, the A switch by default will add those characters, so it's no mystery.

man grep states:

-A NUM

    Places  a  line  containing  a  group  separator  (--)   between
    contiguous  groups  of  matches.  With the -o or --only-matching
    option, this has no effect and a warning is given.

But you can use a simple sed to clean up the result:

yourgrep | sed '/^--$/d'

Solution 4 - Grep

There is no need to pipe to so many greps or use other tools (for example, sed) if you use AWK:

awk '/nmse_gain_constant/{getline;print }' compare.txt

Solution 5 - Grep

One solution will be:

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

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
QuestionMichaelView Question on Stackoverflow
Solution 1 - GrepErik AronestyView Answer on Stackoverflow
Solution 2 - GrepShaohua LiView Answer on Stackoverflow
Solution 3 - GrepEddieView Answer on Stackoverflow
Solution 4 - Grepghostdog74View Answer on Stackoverflow
Solution 5 - GrepAmirshkView Answer on Stackoverflow