user1018279
user1018279

Reputation: 131

Perl regex single quote

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

Upvotes: 12

Views: 10893

Answers (2)

Ilmari Karonen
Ilmari Karonen

Reputation: 50328

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

Upvotes: 18

mu is too short
mu is too short

Reputation: 434635

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.

Upvotes: 6

Related Questions