grep - print line before, don't print match

前端 未结 3 989
青春惊慌失措
青春惊慌失措 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: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.

提交回复
热议问题