Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete 5 lines before and 6 lines after pattern match using Sed?

Tags:

linux

grep

unix

sed

I want to search for a pattern "xxxx" in a file and delete 5 lines before this pattern and 6 lines after this match. How can i do this using Sed?

like image 569
AtoZ Avatar asked Dec 01 '25 21:12

AtoZ


1 Answers

This might work for you (GNU sed):

sed ':a;N;s/\n/&/5;Ta;/xxxx/!{P;D};:b;N;s/\n/&/11;Tb;d' file

Keep a rolling window of 5 lines and on encountering the specified string add 6 more (11 in total) and delete.

N.B. This is a barebones solution and will most probably need tailoring to your specific needs. Questions such as: what if there are multiple string throughout the file? What if the string is within the first five lines or multiple strings are within five lines of each other etc etc etc.

like image 69
potong Avatar answered Dec 04 '25 10:12

potong



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!