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

前端 未结 5 2056
我在风中等你
我在风中等你 2020-12-13 05:27

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.

相关标签:
5条回答
  • 2020-12-13 06:05

    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
    
    0 讨论(0)
  • 2020-12-13 06:08

    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.

    0 讨论(0)
  • 2020-12-13 06:14

    One solution will be:

    grep -A 1 nmse_gain_constant compare.txt | grep -v nmse_gain_constant  | grep -v "\-\-"
    
    0 讨论(0)
  • 2020-12-13 06:22

    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.

    0 讨论(0)
  • 2020-12-13 06:28

    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'
    
    0 讨论(0)
提交回复
热议问题