Perl one insert for searching and replacing a variable in a file

I am trying to find <li ><a href='xxxxxxxx'>some_link</a></li> and replace it with nothing. To do this, I run the command below, but it recognizes $ as part of the regular expression.

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

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

Any ideas? Thanks.

+7
source share
2 answers

Bash only replaces the variable with double quotes.

This should work:

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

EDIT Actually, this may seem strange with \n . Another approach is to use bash concatenation. This should work:

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

EDIT 2: I just carefully considered what you are trying to do, and this is dangerous. You are using a greedy form .* , Which can fit much larger text than you want. Use .*? Instead . I updated the above expressions.

+8
source

If "SOMEVAR" is indeed an external variable, you can export it to the environment and reference it this way:

 SOMEVAR=whatever perl -p -i -e 's/<li ><a href=.*$ENV{SOMEVAR}.*li>\n//g' file.html 
+1
source

All Articles