Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex single quote

Tags:

regex

shell

perl

Can someome help me to run the command below. I also tried to escape the single quotes but no luck.

perl -pi.bak -e 's/Object\.prototype\.myString='q'//' myfile.html
like image 784
user1018279 Avatar asked Oct 30 '11 22:10

user1018279


2 Answers

The problem is not with Perl, but with your shell. To see what's happening, try this:

$ echo 's/Object\.prototype\.myString='q'//'
s/Object\.prototype\.myString=q//

To make it work, you can replace each single quote with '\'', like this:

$ echo 's/Object\.prototype\.myString='\''q'\''//'
s/Object\.prototype\.myString='q'//

or you can save a few characters by writing just:

$ echo 's/Object\.prototype\.myString='\'q\''//'
s/Object\.prototype\.myString='q'//

or even just:

$ echo 's/Object\.prototype\.myString='\'q\'//
s/Object\.prototype\.myString='q'//

or even:

$ echo s/Object\\.prototype\\.myString=\'q\'//
s/Object\.prototype\.myString='q'//

Double quotes, as suggested by mu is too short, will work here too, but can cause unwanted surprises in other situations, since many characters commonly found in Perl code, like $, ! and \, have special meaning to the shell even inside double quotes.

Of course, an alternative solution is to replace the single quotes in your regexp with the octal or hex codes \047 or \x27 instead:

$ perl -pi.bak -e 's/Object\.prototype\.myString=\x27q\x27//' myfile.html
like image 92
Ilmari Karonen Avatar answered Oct 14 '22 09:10

Ilmari Karonen


Double quotes should work:

perl -pi.bak -e "s/Object\.prototype\.myString='q'//" myfile.html

You may or may not want a g modifier on that regex. And you'll probably want to do a diff after to make sure you didn't mangle the HTML.

like image 42
mu is too short Avatar answered Oct 14 '22 09:10

mu is too short