简体   繁体   中英

perl one liner to replace part of file with other file

I'm having problems with this one liner:

perl -pe 's/FINDME/`cat rep.txt`/ge' in.txt

If i use it exactly like this, it works, but I also want to add some text before and after the replaced content:

perl -pe 's/FINDME/SOMETHING1`cat rep.txt`SOMETHING2/ge' in.txt

I get the error:

syntax error at -e line 1, near "SOMETHING1`cat rep.txt`"

Shouldn't the output of the command be treated like a string?

Adicionally, I'm also confused by the fact I can't replace to something with the character <

perl -pe 's/SOMETHING/<SOMETHINGELSE/ge' in.txt
Unterminated <> operator at -e line 1.

Escaping the < (\\<) gives me the same error.

The problem is that you are using the e modifier to the regexp, which means to eval{} (or in other words, execute) the replacement string as a code snippet, but you are treating it like a shell replacement. The e modifier expects CODE, not TEXT.

So, a normal (global) replace would use:

s/FINDME/REPLACE/g

... and this is fine. However, when you use an e flag, the replacement is run as code. Thus:

s/FINDME/`cat foo.txt`/ge;

... is equivalent to ...

$replace = `cat foo.txt`;
s/FINDME/$replace/g;

So, you can see how this:

s/FINDME/SOMETHING`cat foo.txt`/ge;

... is equivalent to...

$replace = SOMETHING`cat foo.txt`;
s/FINDME/$replace/g;

... and this is clearly a syntax error. Try this way instead:

s/FINDME/"SOMETHING".`cat foo.txt`/ge;

and you will find that it works, because this is valid code:

$replace = "SOMETHING".`cat foo.txt`;

( You can of course put even more complex things in there; since what is going on behind the scenes is an eval{}, your code is actually doing this:

eval { "SOMETHING".`cat foo.txt`; }
s/FINDME/$_/g;

however I'm simplifying for ease of comprehension :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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