Losing $1 and $2 variables in my search and replace expression

L

laredotornado

Hi,

I'm using Perl 5.12.3 on Mac 10.7.4. I have a file with lines that look like

AK=Alaska
AL-Alabama
....

and when I run this search and replace expression

perl -pi -e "s/(..)=(.*)/INSERT INTO cb_states (ABBREV, NAME) VALUES ('$1', '$2');/g" states.properties

The values of "$1" and "$2" result in empty strings in my file. That is, the output in the file is

INSERT INTO cb_states (ABBREV, NAME) VALUES ('', '');
INSERT INTO cb_states (ABBREV, NAME) VALUES ('', '');

What is the correct way to write the command line expression above to properly insert the matched values? Thanks,- Dave
 
R

Rainer Weikusat

I'm using Perl 5.12.3 on Mac 10.7.4. I have a file with lines that look like

AK=Alaska
AL-Alabama
...

and when I run this search and replace expression

perl -pi -e "s/(..)=(.*)/INSERT INTO cb_states (ABBREV, NAME) VALUES ('$1', '$2');/g" states.properties

The values of "$1" and "$2" result in empty strings in my file. That is, the output in the file is

INSERT INTO cb_states (ABBREV, NAME) VALUES ('', '');
INSERT INTO cb_states (ABBREV, NAME) VALUES ('', '');

What is the correct way to write the command line expression above
to properly insert the matched values?

Since the script is a double-quoted string, the shell will do variable
interpolations on it before passing it to perl, substituting its $1
and $2 into the expresssion. Since you want perl to do the
substituation, you need to stop the shell from doing so. One way:

"s/(..)=(.*)/INSERT INTO cb_states (ABBREV, NAME) VALUES ('\$1', '\$2');/g"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top