views:

138

answers:

1

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?

+5  A: 

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 -> "
jrockway
Still after replacement the backslash is missing. The following are see in files after replacement.Else FILE_WRITE("C:TestDirmes.txt","Message received");
Prabhu. S
You have to escape the slashes from Perl too.
jrockway
Single quotes don't mean anything to the Windows cmd.exe shell so you can't use them to quote your arguments.
Adrian Pronk
A handy thing is that, in many places, Windows will accept 'C:/TestDir/mes.txt' instead of 'C:\TestDir\mes.txt'. That might make it easier to handle the quoting.
Gaurav