简体   繁体   English

使用 perl 有选择地更改行

[英]Using perl to selectively change lines

Trying to selectively change all line in a file with many other lines.试图用许多其他行有选择地更改文件中的所有行。

input:输入:

    abc  
    PASSWORD=123  
    xyz

desired output;期望的输出;

    abc
    PASSWORD *redacted*
    xyz

Here is the perl one-liner I am using.这是我正在使用的 perl 单行代码。 I have tried a few variations on it, but results are not as desired.我已经尝试了一些变体,但结果并不如预期。

perl -i.bak  -pe '{if (/PASSWORD/) {print  "PASSWORD *redacted*"}else {print "$_"}}' yme.conf

(note the -i.bak is necessary on Solaris). (注意 -i.bak 在 Solaris 上是必需的)。

What I get from that script is:我从该脚本中得到的是:

    abc
    abc
    PASSWORD=*redacted*   PASSWORD=123
    xyz
    xyz

I have many files to do here (*.conf).我这里有很多文件要处理 (*.conf)。

Since -p means print, there is no reason to use print again.由于-p表示打印,因此没有理由再次使用print The following uses the substitution operator to replace everything after the word PASSWORD with *redacted* :以下使用替换运算符将单词PASSWORD之后的所有内容替换为*redacted*

perl -i.bak -pe 's/(PASSWORD).*/$1 *redacted*/' yme.conf

You're getting extra output because the -p option already prints $_ automatically.你得到了额外的输出,因为-p选项已经自动打印$_ You can fix your original code by using -n instead (and adding \n to the redacted string):您可以改用-n来修复原始代码(并将\n添加到编辑后的字符串):

perl -i.bak -ne 'if (/PASSWORD/) {print "PASSWORD *redacted*\n"} else {print $_}' yme.conf

This can be simplified by using -p :这可以通过使用-p来简化:

perl -i.bak -pe 'if (/PASSWORD/) {$_ = "PASSWORD *redacted*\n"}' yme.conf

We loop over the input lines, with the current line being stored in $_ .我们遍历输入行,当前行存储在$_中。 If it contains PASSWORD , we overwrite it.如果它包含PASSWORD ,我们将覆盖它。 The -p option automatically outputs $_ at the end of the loop, which is then either the original line or our redacted version. -p选项在循环结束时自动输出$_ ,这就是原始行或我们的编辑版本。

$variable =~ s/PASSWORD/PASSWORD redacted /g; $variable =~ s/PASSWORD/密码编辑/g;

This will change the desired line globally.这将全局更改所需的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM