6

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

EmpireJones
  • 358
  • 1
  • 4
  • 13

6 Answers6

6
sed '\:// START TEXT:,\:// END TEXT:d' file
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148
2

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.

Andy Lester
  • 740
  • 5
  • 16
1
#!/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

user9517
  • 114,104
  • 20
  • 206
  • 289
1

Perl:

perl -ne '$t=1 if /^\/\/ START TEXT/; print if !$t; $t=0 if /^\/\/ END TEXT/' < sometextfile >anothertextfile
Florian Diesch
  • 1,794
  • 1
  • 11
  • 5
1

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 
Kyle Brandt
  • 82,107
  • 71
  • 302
  • 444
  • Little bit more tricky question, same sort of line by line state problem: http://serverfault.com/questions/90294/search-and-delete-lines-matching-a-pattern-along-with-comments-in-previous-line-i . Worth reading well you are in the mindset I think. – Kyle Brandt May 02 '10 at 18:39
0

gawk:

BEGIN {
  s = 0
}

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

s == 1 {
  next
}

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

{
  print
}
Ignacio Vazquez-Abrams
  • 45,019
  • 5
  • 78
  • 84