I have a script ~/bin/script

$ cat ~/bin/script

perl -pe 's/loremipsum/`cat ~/foo/bar/file.txt`/ge' -i ~/path/to/target.txt

The script is supposed to replace every instance of loremipsum in target.txt with the contents of file.txt. However, issuing script returns

Backticks found where operator expected at -e line 1, at end of line
    (Missing semicolon on previous line?)
Can't find string terminator "`" anywhere before EOF at -e line 1.

What is wrong with my script?


You should store your backtick result in a script variable and use it in the perl call, like

REPL = `cat ~/foo/bar/file.txt`
perl -pe "s/loremipsum/$REPL/ge" -i ~/path/to/target.txt

But I think it would be better to use a perl script only to replace the string with the content of a file, because the content of foo/bar/file.txt can damage your command.


Try this instead:


perl -pe "s/loremipsum/`cat ~/foo/bar/file.txt`/ge" -i ~/path/to/target.txt

Seems like you have problems with the singles quotes.


The issue is resolved by replacing ~ with the path to your home directory.

Or, you could use

perl -pe '$thing=`cat "$ENV{HOME}/file.txt"`;s/loremipsum/$thing/g' target.txt

or some other, nicer, construct that first reads the contents of your file and then replaces the string with that value.

sed is another choice of tool for this, and it even has a special command to read in another file:

sed '/loremipsum/{
         r file.txt
     }' target.txt

This replaces the line that contains the text loremipsum with the contents of file.txt.

Given the file target.txt,

some text
some text loremipsum
some more text

and the file file.txt,

This text
is inserted

the command would produce

some text
This text
is inserted
some more text

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.