I’m having trouble with a backreference in my replacement text that is followed by a literal. I have tried the following:
perl -0pi -e "s/(<tag1>foo<\/tag1>\n\s*<tag2>)[^\n]*(<\/tag2>)/\1${varWithLeadingNumber}\2/" file.xml
perl -0pi -e "s/(<tag1>foo<\/tag1>\n\s*<tag2>)[^\n]*(<\/tag2>)/\g{1}${varWithLeadingNumber}\g{2}/" file.xml
The first of course causes problems because ${varWithLeadingNumber} begins with a number, but I thought the \g{1} construct in my second attempt above was supposed to solve this problem. I’m using perl 5.12.4.
Using
\1,\2, etc in the replacement expression is wrong.\1is a regular expression pattern that means “match what the first capture matched” which makes no sense in a replacement expression. Regular expression patterns should not be used outside of regular expressions!$1,$2, etc is what you should be using there.After fixing
\1, you haveThat said, I think
varWithLeadingNumberis supposed to be a shell variable? You shouldn’t have any problems if it’s a Perl variable. If you’re having the shell interpolatevarWithLeadingNumber, the problem can be fixed usingNote that you will have problems if $varWithLeadingNumber contains “$”, “@”, “\” or “/”, so you might want to use a command line argument instead of interpolation.
You could also use an environment variable.
or
If you did have a
\1you can avoid the problem a number of ways including