Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl one liner to find and replace in a file with a variable

I'm trying to find <li ><a href='xxxxxxxx'>some_link</a></li> and replace it with nothing. To do this, I'm running the command below but it's recognizing $ as part of a regex.

perl -p -i -e 's/<li ><a href=.*$SOMEVAR.*li>\n//g' file.html

I've tried the following things,
${SOMEVAR}
\$SOMEVAR
FIND="<li ><a href=.*$SOMEVAR.*li>"; perl -p -i -e 's/$FIND//g' file.html

Any ideas? Thanks.

like image 854
user1017351 Avatar asked Oct 27 '11 21:10

user1017351


2 Answers

Bash only does variable substitution with double quotes.

This should work:

perl -p -i -e "s/<li ><a href=.*?$SOMEVAR.*?li>\n//g" file.html

EDIT Actually, that might act weird with the \n in there. Another approach is to take advantage of Bash's string concatenation. This should work:

perl -p -i -e 's/<li ><a href=.*?'$SOMEVAR'.*?li>\n//g' file.html

EDIT 2: I just took a closer look at what you're trying to do, and it's kind of dangerous. You're using the greedy form of .*, which could match a lot more text than you want. Use .*? instead. I updated the above regexes.

like image 184
Chriszuma Avatar answered Sep 19 '22 13:09

Chriszuma


If "SOMEVAR" is truly an external variable, you could export it to the environment and reference it thus:

SOMEVAR=whatever perl -p -i -e 's/<li ><a href=.*$ENV{SOMEVAR}.*li>\n//g' file.html
like image 45
JRFerguson Avatar answered Sep 17 '22 13:09

JRFerguson