grep - print line before, don't print match

前端 未结 3 988
青春惊慌失措
青春惊慌失措 2020-12-17 21:31

How to easily print line above the match and skip the match itself? grep -A, -B and -o opt do not solve it. Maybe some

相关标签:
3条回答
  • 2020-12-17 22:09
    awk '/foo/{print a}{a=$0}' your_file
    
    0 讨论(0)
  • 2020-12-17 22:11
    awk '!/foo/ { line = $0 }
         /foo/ { print line }' foo.txt
    

    The first clause saves each non-foo line in a variable. The second clause prints the most recent saved line when the line matches foo.

    This also works (and handles the case where you have two foo lines in a row):

    awk '/foo/ {print line}
         {line = $0}' foo.txt
    

    With grep you can do:

    grep -B 1 foo foo.txt | grep -vE 'foo|^--$'
    

    The second command filters out the foo lines and the dividers that are printed between the matching blocks.

    0 讨论(0)
  • 2020-12-17 22:22

    Just set p to the pattern you want:

    $ awk '$0~p{print a}{a=$0}' p="foo" file
    bar
    baz
    foo
    
    0 讨论(0)
提交回复
热议问题