Glam Prestige Journal

Bright entertainment trends with youth appeal.

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?

4 Answers

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.

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.

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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