Frage

I have a file that is something like below.

I want to grep for a string say cde and find two lines above it and delete in the same file (something like perl -i).

abc
abc
cde
fgh
lij
lij
klm
mno
pqr
pqr

I tried

grep -B 2 "cde" a.txt

Output

abc
abc
cde

But now I want to delete the two lines above cde so that my final output is

cde
fgh
lij
lij
klm
mno
pqr
pqr

I have tried

grep -v -B  "cde" a.txt

but it doesn't work

War es hilfreich?

Lösung

In a perl one-liner

perl -ne 'push @b, $_; @b = () if /^cde$/; print shift @b if @b == 3; END { print @b }' file.txt

Andere Tipps

Here is an awk solution.

awk 'FNR==NR {if (/cde/) f=NR;next} FNR!=f-1 && FNR!=f-2' file{,} > tmp && mv tmp file
cde
fgh
lij
lij
klm
mno
pqr
pqr

file{,} is the same as file file. Make awk read the file two times.
First time look for cde and store it in a variable f
Second time print if record is not -1 or -2 compare to the finding
> tmp && mv tmp file store output in a tmp file, then write back to original file, like -i

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top