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

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


You want to do something very similar to the answer given

sed -n '/page . of ./ { #when pattern matchesn #read the next line into the pattern spacex #exchange the pattern and hold spaced #skip the current contents of the pattern space (previous line)}x  #for each line, exchange the pattern and hold space1d #skip the first linep  #and print the contents of pattern space (previous line)$ { #on the last linex #exchange pattern and hold, pattern now contains last line readp #and print that}'

And as a single line

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


grep -v -B1 doesnt work because it will skip those lines but will include them later on (due to the -B1. To check this out, try the command on:

**document 1**                         -> 1**page 1 of 2**                        -> 2**document 1****page 2 of 2****page 3 of 2**

You will notice that the page 2 line will be skipped because that line won't be matched and the next like wont be matched.

There's a simple awk solution:

awk '!/page.*of.*/ { if (m) print buf; buf=$0; m=1} /page.*of.*/ {m=0}' 1.txt

The awk command says the following:

If the current line has that "page ... of ", then it will signal that you haven't found a valid line. If you do not find that string, then you print the previous line (stored in buf) and reset the buffer to the current line (hence forcing it to lag by 1)


grep -vf <(grep -B1 "page.*of" file | sed '/^--$/d') file