Makesh
Makesh

Reputation: 1234

unmatched parenthesis in regex - Linux

I want to replace (whole string)

    $(TOPDIR)/$(OSSCHEMASDIRNAME)

with

    /udir/makesh/$(OSSCHEMASDIRNAME)

in a makefile

I tried with

     perl -pi.bak -e "s/\$\(TOPDIR\)\/\$\(OSSCHEMASDIRNAME\)/\/udir\/makesh\/\$\(OSSCHEMASDIRNAME\)/g " makefile

but i am getting unmatched parentheses error

Upvotes: 1

Views: 368

Answers (3)

TLP
TLP

Reputation: 67900

When in doubt about escaping, you can simply use quotemeta or \Q ... \E.

perl -pe 's#\Q$(TOPDIR)\E(?=/\Q$(OSSCHEMASDIRNAME)\E)#/udir/makesh#;'

Note the use of a look-ahead assertion to save us the trouble of repeating the trailing part in the substitution.

A quotemeta solution would be something like:

perl -pe 'BEGIN { $dir = quotemeta(q#$(TOPDIR)/$(OSSCHEMASDIRNAME)#); }
          s#$dir#/udir/makesh/$(OSSCHEMASDIRNAME)#;'

Of course, you don't need to use an actual one-liner. When the shell quoting is causing troubles, the simplest option of them all is to write a small source file for your script:

s#\Q$(TOPDIR)\E(?=/\Q$(OSSCHEMASDIRNAME)\E)#/udir/makesh#;

And run with:

perl -p source.pl inputfile

Upvotes: 1

OmnipotentEntity
OmnipotentEntity

Reputation: 17131

First off, you don't need to use / for regular expressions. They're just canonical. You can use pretty much anything. Thus your code can become (simplify away some \):

perl -pi.bak -e "s|\$\(TOPDIR\)/\$\(OSSCHEMASDIRNAME\)|/udir/makesh/\$\(OSSCHEMASDIRNAME\)|g " makefile

Now to actually address your issue, because you're using " instead of ', the shell attempts to figure out what $\ means which is then replaced with (presumably) nothing. So what you really want is:

perl -p -i.bak -e 's|\$\(TOPDIR\)/\$\(OSSCHEMASDIRNAME\)|/udir/makesh/\$\(OSSCHEMASDIRNAME\)|g' makefile

Upvotes: 2

jfreax
jfreax

Reputation: 103

You have to "double" escape the dollar sign. Like this:

echo "\$(TOPDIR)/\$(OSSCHEMASDIRNAME)" | perl -p -e "s/\\$\(TOPDIR\)\/\\$\(OSSCHEMASDIRNAME\)/\/udir\/makesh\/\\$\(OSSCHEMASDIRNAME\)/g"

Upvotes: 2

Related Questions