How can I remove all instances of tagged blocks of text in a file with sed, grep, or another program?

If I have a file which contains:

random
text
// START TEXT
internal
text
// END TEXT
more
random
// START TEXT
asdf
// END TEXT
text

how can I remove all blocks of text within the start/end lines, produce the following?

random
text
more
random
text

link|improve this question

feedback

6 Answers

up vote 3 down vote accepted
sed '\:// START TEXT:,\:// END TEXT:d' file
link|improve this answer
feedback

The proper way to do this in Perl is with Perl's flip-flop operator

perl -ne'print unless m{^// START TEXT}..m{^// END TEXT}'

x..y in Perl evaluates to true starting with x is true, and ending when y is true. The m{} is another way to write a regular expression match so we don't have to go crazy backslashing all your forward slashes.

link|improve this answer
feedback

gawk:

BEGIN {
  s = 0
}

s == 1 && $0 ~ /^\/\/ END TEXT$/ {
  s = 0
  next
}

s == 1 {
  next
}

/^\/\/ START TEXT$/ {
  s = 1
  next
}

{
  print
}
link|improve this answer
feedback
#!/usr/bin/nawk -f
BEGIN {
startblock="^/\/\ START TEXT"
endblock="^/\/\ END TEXT"
}
{
        if(! match($0,startblock)) {
                { print }
        }
        else    {
                while ( !match($0,endblock )) {
                        getline;
                }
        }

}

./removeblocks < sometextfile >anothertextfile

link|improve this answer
feedback

Perl:

perl -ne '$t=1 if /^\/\/ START TEXT/; print if !$t; $t=0 if /^\/\/ END TEXT/' < sometextfile >anothertextfile
link|improve this answer
feedback

Simple State Machine:

#!/usr/bin/perl

my $inblock = 0;
while (<>) {
    if (/^\/\/ START TEXT/) {
        $inblock=1;
    } elsif (/^\/\/ END TEXT/) {
        $inblock=0;
    } elsif ( ! $inblock) {
        print;
    }
}

Example Usage:

cat testfile | perl remove_block.pl
random
text
more
random
text

Although Florian's logic is sound I believe with your example, it will print //END TEXT with the following (malformed) input:

random
text
// START TEXT
internal
text
// END TEXT
// END TEXT
more
random
// START TEXT
asdf
// END TEXT
text 
link|improve this answer
Little bit more tricky question, same sort of line by line state problem: serverfault.com/questions/90294/… . Worth reading well you are in the mindset I think. – Kyle Brandt May 2 '10 at 18:39
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.