简体   繁体   中英

Why are my backslashes disappearing in my Perl one-liner?

I tried a search and replace across all files in a directory as follows:

/usr/bin/perl -p -i -e "s/Else/Else  FILE_WRITE(\"C:\\TestDir\\mes.txt","Message received");/g"            *.scr

That is replace all occurence of Else with "Else FILE_WRITE(\\"C:\\TestDir\\mes_.txt","Message received");"

But the replacement is seen to be as follows:

Else  FILE_WRITE("C:TestDir^@mes.txt); 

What am I missing?

This is actually a shell question, not a Perl question.

You need to escape the slashes in the filename, otherwise the shell will interpret them as escape sequences.

What you have right now:

$ echo "s/Else/Else FILE_WRITE(\"C:\TestDir\mes.txt","Message received");/g"
bash: syntax error near unexpected token `)'

What you want:

$ echo "s/Else/Else FILE_WRITE(\"C:\\TestDir\\mes.txt\",\"Message received\");/g"
s/Else/Else FILE_WRITE("C:\TestDir\mes.txt","Message received");/g

In the future, try to use single quotes instead of double quotes. Then you can write without escaping:

$ echo 's/Else/Else FILE_WRITE("C:\TestDir\mes.txt","Message received");/g'
s/Else/Else FILE_WRITE("C:\TestDir\mes.txt","Message received");/g

Perl's flexible q and qq operators are also helpful:

$ perl -e 'print q{A double quote looks like this -> "}'
A double quote looks like this -> "

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