Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

RegExp using variables like \1 \2 and concat that value with a number 1

Status
Not open for further replies.

perlcamp

Programmer
Aug 12, 2010
6
0
0
US
I have records in a file that look like this:
IPOD,YAHOO,0033092909,50/4Z1,technology_102

I would like to convert the 4Z1 to 42001 so the complete record would look like this:

IPOD,YAHOO,0033092909,50/42001,technology_

So essentially what I am trying to do is find records that have a slash / and then one or more digits followed by Z1, and convert the Z1 value to 2001, while retaining the /and the digits that proceeded the Z.

What I have tried is:

perl -pi -e "s#((/\d)Z1,)#\22001,#g" test

But I get:
IPOD,YAHOO,0033092909,50\22001,technology_102

so the value stored in \2 is getting lost.

if i try this perl command (thinking i need to concat the values together) I get a mysterious 4 (how?) followed by a period and then 2001 :
perl -pi -e "s#((/\d)Z1,)#\2.2001,#g"

IPOD,YAHOO,0033092909,50/4.2001,technology_102

Can someone help with this and explain what I am missing in the concept of using the /1 .../n values when wanting to put them with digits.
 
I think you might be trying to make that too complicated. Try something like:
Code:
-e "s#(/\d+)Z1,#${1}2001,#g"
I don't remember exactly where it is in the perdocs (though I suspect you can find it in perldoc perlre) but you probably want to use $1 on the substitution portion of that regex. I wrote it as ${1} so it doesn't try to use the variable $12001, which wouldn't do you any good.
 
I actually did figure this out right before reading your post but it isn't as nice as yours:

perl -pi -e "s#((/\d)Z1,)#${2}2001,#g"

i did this after reading about limitations of using /n and that $n instead

The comment pertained to being outside the pattern. I admit I don't fully understand the statement...

"When the bracketing construct ( ... ) is used, \<digit> matches the digit'th substring. Outside of the pattern, always use ``$'' instead of ``\'' in front of the digit. (While the \<digit> notation can on rare occasion work outside the current pattern, this should not be relied upon.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top