views:

110

answers:

4

How would I delete the 6 lines starting from every instance of a word i see?

+5  A: 

I think this sed command will do what you want:

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

It removes any line containing the text bar plus the five following lines.

Run as above to see the output. When you know it is working correctly use the switch --in-place=.backup to actually perform the change.

Mark Byers
+1 OP should bear in mind that this deletes "front to back", that is, if `bar` appears within five lines following `bar`, that subsequent `bar` will be deleted before it has the chance to "define" six lines to delete. Probably acceptable, but something to keep in mind.
pilcrow
- had an awk sniipet here - thought better of it.
jim mcnamara
+3  A: 

This simple perl script will remove every line that containts word "DELETE6" and 5 consecutive lines (total 6). It also saves previous version of file in 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--;
}

HTH

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

Note that if my_word occurs in the skipped-over lines, the counter will not be reset.

Sean