Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

6 Answers

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

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.

share|improve this answer
add comment
#!/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

share|improve this answer
add comment

Perl:

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

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 
share|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
add comment

gawk:

BEGIN {
  s = 0
}

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

s == 1 {
  next
}

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

{
  print
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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