I have two Perl one liners:
perl -pe "s/\b$a\b/$b/g if m/param1 /" test
and
perl -pe "s/\b$a\b/$b/g unless /^#/" test
How can I combine theif m/somthing/
and the unless /something/
, like:
[root@localhost tmp]# 开发者_运维知识库 perl -pe "s/\b$a\b/$b/g if m/param1/ unless /^#/" test
syntax error at -e line 1, near "m/param1/ unless"
Maybe
perl -pe "s/\b$a\b/$b/g if m/param1/ && ! /^#/" test
does it.
unless
is the same as if not
. Judging by the way you've written the statement, I'm guessing you mean the following:
perl -pe "s/\b$a\b/$b/g if m/param1/ and not /^#/" test
(Although, you might have meant or
instead of and
?)
On an unrelated note, you may want to add the \Q
and \E
escape sequences around $a
in your regex:
perl -pe "s/\b\Q$a\E\b/$b/g if m/param1 /" test
They escape any characters that are special to regexes. If you intend for $a
to hold a regex you should probably move the word boundary assertions (\b
) into it.
No matter what you choose to do, you will need to be careful with values in $a
and $b
. For instance:
a="/"
b="slash"
perl -pe "s/\b\Q$a\E\b/$b/g if m/param1 /" test
will cause a syntax error. One solution to this is to not use environment variables to replace code. Perl allows you access to the environment through the %ENV
hash:
perl -pe 's/\b\Q$ENV{a}\E\b/$ENV{b}/g if m/param1 /' test
Notice the use of single ticks to avoid treating $ENV
as a shell variable.
精彩评论