Removing N lines from each starting point

How can I delete 6 lines, starting with each instance of the word that I see?

+4
source share
4 answers

I think this sed command will do what you want:

sed '/bar/,+5d' input.txt 

It deletes any line containing the text bar plus the next five lines.

Run as above to see the result. When you know that it works correctly, use the --in-place=.backup to actually make the change.

+5
source

This simple perl script will delete every line containing the word "DELETE6" and 5 consecutive lines (total 6). It also saves the previous version of the file to FILENAME.bak. To run the script:

perl script.pl FILE_TO_CHANGE

 #!/usr/bin/perl use strict; use warnings; my $remove_count = 6; my $word = "DELETE6"; local $^I = ".bak"; my $delete_count = 0; while (<>) { $delete_count = $remove_count if /$word/; print if $delete_count <= 0; $delete_count--; } 

NTN

+3
source
 perl -i.bak -n -e '$n ++; $n = -5 if /foo/; print if $n > 0' data.txt 
+1
source
 perl -ne 'print unless (/my_word/ and $n = 1) .. ++$n == 7' 

Note that if my_word occurs in missing lines, the counter will not reset.

0
source

Source: https://habr.com/ru/post/1312622/


All Articles