Spooferman
Spooferman

Reputation: 353

How to avoid the comment lines for parsing during string replacement in a file?

I am unable to avoid the comment lines(lines starting with *) for parsing during string replacement in a file. Please help me with my code.

`perl -pi.bak -e "$_ =~/[#.*]*/; /s/PATTERN/REPLACEMENT STRING/g" Test.txt`;

Am using Perl in Eclipse,Windows XP.

I get the following Error message:

Number found where operator expected at -e line 6, near "*    LAST UPDATED 09/15"
(Might be a runaway multi-line // string starting on line 1)
(Missing operator before 15?)
Bareword found where operator expected at -e line 6, near "1994 AT"
(Missing operator before AT?)

Thanks in Advance, Perl Newbie

Upvotes: 0

Views: 3332

Answers (4)

mirod
mirod

Reputation: 16171

use next to skip the following code if you match a comment:

perl -i.back -p -e'next if /^#/; s/PATTERN/REPLACEMENT STRING/' Test.txt

update: now as choroba suggested, instead of launching a separate instance of Perl and having to deal with quotes, you should probably have the whole thing in your main code:

my $file= 'Test.txt';
my $bak= "$file.bak";

rename $file, $bak or die "cannot rename $file into $bak: $!";;

open( my $in,  '<', $bak)  or die "cannot open $bak: $!";
open( my $out, '>', $file) or die "cannot create $file: $!";

while( <$in>)
  { if( ! /^\*/) # note the backslash here, * is a meta character
      { s/PERFORM \Q$func[5]\E\[\.\]*/# PERFORM $func[5]\.\n $hash{$func[5]}/g; }
    print {$out} $_;
  }
close $in; 
close $out;

Note that $func[5] can (potentially) includes meta-characters, so I used \Q and \E to escape them.

I am not sure about the \[\.\]* part, which as written matches a square bracket, a dot, and 0 or more closing square brackets: [., [.], or [.]]. I suspect that's not what you want.

Upvotes: 0

unkaitha
unkaitha

Reputation: 225

I use this to skip the lines that match the regex

perl -ne 'print unless /^\*/' filename

Upvotes: 1

Yi Zhao
Yi Zhao

Reputation: 6784

Try this if you try to skip any lines which starting with '*' as the comments:

perl -pi.bak -e "s/PATTERN/REPLACEMENT STRING/g unless /^\*/" Test.txt

When processing a file like this:

* this is a comments: AAA => BBB
AAA
AAB
ABB
BBB

run

perl -pi.bak -e "s/AAA/BBB/g unless /^\*/" Test.txt

you will get

* this is a comments: AAA => BBB
BBB
AAB
ABB
BBB

Only the AAA in the normal context will be replaced.

Upvotes: 0

choroba
choroba

Reputation: 241968

You should do the replacement only if the string does not match:

perl -pi.bak -e "s/PATTERN/REPLACEMENT STRING/g unless /^#/" Test.txt

Also, it seems you are trying to call Perl from Perl. That is usually slower than processing the file from inside your original program.

Upvotes: 2

Related Questions