Issue
I have a log file which contains several repeats of the pattern Fre --
. I need to remove only first occurrence of this pattern and the next 20 lines after that and keep other matches intact. I need to do it in a bash terminal, using sed
preferably or awk
or perl
. I would highly appreciate your help.
I tried
sed -e '/Fre --/,+20d' log.log
but it deletes all the patterns and next 20 lines after that. I want only first pattern to be removed
There is a more or less similar question and some answers here: How to remove only the first occurrence of a line in a file using sed but I don't know how to change it to remove 20 lines after the first match
Solution
Pretty sure that someone will find a nice sed
command but I know awk
better.
You can try :
awk '/Fre --/ && !found++{counter=21}--counter<0' log.log
Explanations :
/Fre --/
-> if it finds pattern Fre --
&& !found++
-> and if it didn't find it before
{counter=21}
-> it sets counter value at 21 (because you want to remove the line + the next 20s)
--counter<0
-> decreases the counter and prints the line only if counter < 0
As mentioned by @Sundeep, @EdMorton solution is safer on very big files.
awk '/Fre --/ && !found++{counter=21}!(counter&&counter--)' log.log
NOTE
If you want the deletions to be saved into the original file, you will have to copy the contents of the awk
command into a temp file, and then move the temp file into the original file. Always be careful before editing the original file since you may lose precious informations.
Run the first command first :
awk '/Fre --/ && !found++{counter=21}!(counter&&counter--)' log.log > log.log.tmp
Then check the .tmp file and you can run the second command to apply the changes if .tmp file looks ok :
mv log.log.tmp log.log
Answered By - Corentin Limier Answer Checked By - Senaida (WPSolving Volunteer)