JimR
JimR

Reputation: 513

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. 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).

What I get from that script is:

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

I have many files to do here (*.conf).

Upvotes: 1

Views: 56

Answers (3)

ruchika
ruchika

Reputation: 11

$variable =~ s/PASSWORD/PASSWORD redacted/g;

This will change the desired line globally.

Upvotes: -1

melpomene
melpomene

Reputation: 85767

You're getting extra output because the -p option already prints $_ automatically. You can fix your original code by using -n instead (and adding \n to the redacted string):

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

This can be simplified by using -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. The -p option automatically outputs $_ at the end of the loop, which is then either the original line or our redacted version.

Upvotes: 4

toolic
toolic

Reputation: 62083

Since -p means print, there is no reason to use print again. The following uses the substitution operator to replace everything after the word PASSWORD with *redacted*:

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

Upvotes: 4

Related Questions