Sunday, April 3, 2011

How do I escape a left paren in a Perl regex?

If I have a file containing some escaped parens, how can I replace all instances with an unescaped paren using Perl?

i.e. turn this:

.... foo\(bar ....

into this

.... foo(bar ....

I tried the following but receivied this error message:

perl -pe "s/\\\(/\(/g" ./file
Unmatched ( in regex; marked by <-- HERE in m/\\( <-- HERE / at -e line 1.
From stackoverflow
  • You're forgetting that backslashes mean something to the shell, too. Try using single quotes instead of double quotes. (Or put your script in a file, where you won't need to worry about shell quoting.)

    dmercer : Gah, can't believe I didn't think of that. Friday can't come soon enough.
  • Gah. From command line, no less. Way too many levels of metacharacter interpretation.

    Try replacing your double quotes with single quotes, see if that helps.

    dmercer : Thanks, you're about 8 seconds behind the earlier answer. Cheers
  • cjm's answer is probably the best. If you must do it at the command line, try using quotemeta() or the metaquoting escape sequence (\Q...\E). This worked for me in a bash prompt:

    perl -pe "s/\Q\(\E/(/g" ./file
    

0 comments:

Post a Comment