How do I delete a matching line and the previous one?

前端 未结 4 895
说谎
说谎 2020-12-11 05:13

I need delete a matching line and one previous to it. e.g In file below I need to remove lines 1 & 2.

I tried \"grep -v -B 1 \"page.of.\" 1.txt and I

4条回答
  •  粉色の甜心
    2020-12-11 05:42

    You want to do something very similar to the answer given

    sed -n '
    /page . of ./ { #when pattern matches
    n #read the next line into the pattern space
    x #exchange the pattern and hold space
    d #skip the current contents of the pattern space (previous line)
    }
    
    x  #for each line, exchange the pattern and hold space
    1d #skip the first line
    p  #and print the contents of pattern space (previous line)
    
    $ { #on the last line
    x #exchange pattern and hold, pattern now contains last line read
    p #and print that
    }'
    

    And as a single line

    sed -n '/page . of ./{n;x;d;};x;1d;p;${x;p;}' 1.txt
    

提交回复
热议问题