Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - Why is the escape of quotes lost in this regex substitution?

Why is the escaping of double quotes are lost in this case?

$ cat foo.txt   
This is a "very good" text worth AMOUNT dollars    
$ cat full_story.txt   
This is about money:  
STORY  

Testing it with the following:

VAR=$(cat foo.txt)                                                                                         
TOTAL=$(cat full_story.txt)  
echo "$TOTAL" | perl -pe "s/STORY/$VAR/g"  

Result:

This is about money:  
This is a "very good" text worth AMOUNT dollars  

The escape of double quotes got lost. I was expecting:

This is about money:  
This is a "very good" text worth AMOUNT dollars  

How can I preserve the escapes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that perl parses backslash escapes in an explicit replacement string (not a perl variable), and hence a " is parsed into a". For example:

$ echo "A STORY" | perl -pe 's/STORY/"Hello"/'
A "Hello"

(Note that the Bash variable $VAR does not become a perl variable $VAR , but rather a constant string.) So you need to escape the backslashes like this in constant string:

$ echo "A STORY" | perl -pe 's/STORY/"Hello"/' 
A "Hello"

You can work around the issue by transferring the Bash variable $VAR into a perl variable $VAR by using the -s switch to perl like this:

echo "$TOTAL" | perl -spe 's/STORY/$VAR/g' -- -VAR="$VAR"

Ouput:

This is about money:  
This is a "very good" text worth AMOUNT dollars

Explanation:

  • -s enables switch parsing for user defined switches on the perl command line. Any switch found there is removed from @ARGV and sets the corresponding variable in the Perl program.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...