How to delete the corresponding line and the previous?

I need to delete the corresponding line and one of them. for example, in the file below, I need to delete lines 1 and 2.

I tried "grep -v -B 1" page.of. "1.txt and I did not expect it to print math lines and context.

I tried How to remove the corresponding line, the line above and one below using sed? but could not understand the use of sed.

---1.txt-- **document 1** -> 1 **page 1 of 2** -> 2 testoing testing super crap blah **document 1** **page 2 of 2** 
+6
source share
4 answers

You want to do something very similar to the answer

 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 one line

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

grep -v -B1 does not work because it will skip these lines but turn them on later (due to -B1 . To check this, try the command:

 **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 this line will not be matched, and the next one, as usual, will not match.

There is 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 this "page ...", then it will signal that you did not find a valid line. If you do not find this line, you print the previous line (stored in buf) and reset in the buffer of the current line (therefore, making it lag by 1)

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

Not too familiar with sed, but here is a perl expression to do the trick:

 cat FILE | perl -e '@a = <STDIN>; for( $i=0 ; $i <= $#a ; $i++ ) { if($i > 0 && $a[$i] =~ /xxxx/) { $a[$i] = ""; $a[$i-1] = ""; } } print @a;' 

edit:

where "xxxx" is what you are trying to match.

0
source

Source: https://habr.com/ru/post/897085/


All Articles