简体   繁体   中英

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.

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.

如果“SOMEVAR”确实是一个外部变量,您可以将其导出到环境并引用它:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM