简体   繁体   English

Perl one liner用于在变量文件中查找和替换

[英]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. 我正在尝试找到<li ><a href='xxxxxxxx'>some_link</a></li>并将其替换为<li ><a href='xxxxxxxx'>some_link</a></li> 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. Bash只用双引号进行变量替换。

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. 编辑实际上,这可能与\\n中的\\n有点奇怪。 Another approach is to take advantage of Bash's string concatenation. 另一种方法是利用Bash的字符串连接。 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. 编辑2:我只是仔细看看你想要做什么,这有点危险。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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