-4

anted to comment off those line if found "dummy", how to write a perl to put # like below?

3 Answers3

1

You can do this on a command line with something like this:

cat file | perl -nle 'if (/_dummy/) { print "#". $_ } else { print $_ }'

Or if you prefer a script file (assume the following is saved as commenter.pl):

#!/usr/bin/env perl

foreach my $line (<>) {
    if ($line =~ /dummy/) {
        print "#" . $line;
    } else {
        print $line;
    }
}

And then you can do cat file | ./commenter.pl or ./commenter.pl file

mr rogers
  • 3,147
  • 1
  • 18
  • 28
1

Well, I should also give you the one liner if you want to edit the file in place:

$ perl -pi -e 's/^(.*dummy.*)$/# $1/' <file>

The -i is for in-place editing, -p does a while (<>).

Although I enjoy perl, for something as simple as that in-place file replacement, most people would use sed instead:

$ sed -i.bak -E "s/^(.*dummy.*)$/# \1/" <file>

(works on Linux/BSD/Mac - on Linux only .bak can be omitted which won't save a backup obviously)

Ecuador
  • 914
  • 6
  • 24
1
perl -pe's/^(?=.*dummy)/#/'

or

perl -pe'print "#" if /dummy/'

Specifying file to process to Perl one-liner

ikegami
  • 343,984
  • 15
  • 249
  • 495