LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Delete all lines containing a string, plus 4 lines below it? (http://www.linuxquestions.org/questions/linux-newbie-8/delete-all-lines-containing-a-string-plus-4-lines-below-it-784922/)

RedHelix 01-26-2010 03:48 PM

Delete all lines containing a string, plus 4 lines below it?
 
Hi everyone,
I've come across an unusual requirement for a service in my Ubuntu system.

Simply put, I need to find a way to search for all instances of a term in a file, delete lines containing containing that term, and delete four lines below each instance of that term.

Either that, or copy the entirety of a file to a new file and skip over all lines containing the term plus four below it.

This sounds kinda weird, I know. Without going too far into detail, I either have to change the logfile format for a server I'm running which is a huge pain in the butt, or I can just run a script to edit an HTML report generated from said logs. (Said report is really just for managers to peruse, and I like my log format, so I'm pursuing option 2.)

Thanks in advance!

worm5252 01-26-2010 03:52 PM

Well this is a great thread for me to follow since I am working on my Scripting skills. I know how to find the string in a script, but figuring out how to delete the line and the next 4 lines I do not know how to do. Sounds like using sed or awk might be a good solution here.

GazL 01-26-2010 04:14 PM

sed can do that for you quite easily.

e.g.
Code:

gazl@nix:/tmp$ cat testing
one
two
three
a
b
c
d
four
five
gazl@nix:/tmp$ sed -e '/three/,+4 d' < testing
one
two
four
five
gazl@nix:/tmp$


worm5252 01-26-2010 04:22 PM

I found a 1 liner googling that will do exactly what you want.

Code:

awk '/search string here/{c=2}!(c&&c--)' file >newfile
You can replace search string here with your search string. c= to the number of lines you want to delete. file is the name of the file to search and newfile is the name of the file that will contained the results.

I created a file called TEST with the following contents.
Quote:

the quick brown fox jumped over the fence
a car drove through a bush
trees are healthy
meat is good
this is some random text
I want to search TEST for the string "car drove" and delete that line and 2 lines below it and save the results to a file called RESULTS. I run this command

Code:

awk '/car drove/{c=3}!(c&&c--)' TEST >RESULTS
The outcome is the file RESULTS contains the following text
Quote:

the quick brown fox jumped over the fence
this is some random text

RedHelix 01-27-2010 09:13 AM

Marvelous; thank you sir. Your google skills are strong


All times are GMT -5. The time now is 06:24 AM.