Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I remove a whole block of unwanted text using Unix grep?

Tags:

grep

unix

Had been trying this hard enough but still couldn't figure out any smarter way to do it...

example:

### this is the whole block structure ###
text_text_text
text_text_text
text_text_text
apple
### another block ###
text_text_text
text_text_text
text_text_text
orange

Doing less <file_name> | grep -B3 "apple" | less will return:

text_text_text
text_text_text
text_text_text
apple

but now my requirement is I don't want this block (with apple). I am sure about what I do not want, but not certain about what I want. So I could't do this

less <file_name> | grep -B3 "orange" |less

if I were to:

less <file_name> | grep -v "apple" | less

then only the single line with apple is removed, the block related to apple will be remaining there.

and I tried

less <file_name> | grep -v -B3 "apple" | less

but that doesn't seem working.

So any way to help me remove that block related to apple?

like image 967
user2919338 Avatar asked Jan 01 '26 08:01

user2919338


1 Answers

One way to remove the unwanted block would be to use tac and sed. Saying:

tac <filename> | sed '/apple/,+3d' | tac

would return:

### this is the whole block structure ###
### another block ###
text_text_text
text_text_text
text_text_text
orange

for your sample data.


Explanation: tac reverses lines in a file. /apple/,+3 would match apple and the next 3 lines. d is the delete command.

Since you need to remove the pattern apple and 3 lines before it; we reverse the lines in the files, find apple, delete it and the next 3 lines, and reverse the lines again to get the desired result.

You might also want to refer to the sed manual.

like image 134
devnull Avatar answered Jan 03 '26 14:01

devnull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!