5

I need to replace string SALT in a file with content of another file. Problem is that the input file has multilines. I tried something like this in my bash script:

SALT=`cat salt.txt`;
sed "s/SALT/$SALT/" wp-config.php > result.txt

It work's fine when the salt.txt is single line, but if there are more lines it fails. I've read that it could do PERL. But I don't know how. Could you help me?

1

Another perl way:

perl -pe 's/SALT/`cat salt.txt`/e' wp-config.php > result.txt

The key here is the /e regexp option allowing us to use a perl command result as a substitution string.

1

If you want to stick to bash, choose a character that doesn't appear in neither your string nor in your file, let's say @; then:

SALT=`< salt.txt tr '\n' '@'`
sed "s/SALT/$SALT/" wp-config.php | tr '@' '\n' > result.txt

This way before the replacement the newline characters in your string are changed to @ and after the replacement the @ characters are changed back to newlines, so that SALT is not treated as an array anymore but just as a variable containing a long string.

1

You can do this:

sed -e "/SALT/{r salt.txt" -e "d}" wp-config.php  > result.txt

Where salt.txt is the salt, wp-config.php is the input file and SALT is the string to replace

2
  • 2
    This will replace whole line with content of file salt.txt if containing a SALT in it not SALT word itself!! Mar 30 '15 at 13:49
  • is there anyway to fix this? instead of replacing the whole line, just the keyword Apr 27 '20 at 9:38
0
perl -e 'open my $S, "<", "salt.txt" or die $!;
         $salt = do { local $/ ; <$S> };
         s/SALT/$salt/, print while <>;
        ' wp-config.php > result.txt

The first line opens the salt.txt.
The second line reads it contents into the $salt variable.
The third takes the command line arguments as file names, reads the files line by line and replaces the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.