简体   繁体   English

Perl多行搜索替换

[英]Perl multiline search replace

I want to find and corresponding block and uncomment the second line in text file using perl one-liner. 我想使用perl one-liner在文本文件中找到并阻止和取消注释第二行。 Im fairly new to using complex regex, so your help is very much appreciated! 我对使用复杂的正则表达式还算陌生,非常感谢您的帮助! Also is there a way to debug one-liners? 还有没有一种方法可以调试单线?

Here is what I have so far, which does not work even though I tested it using a interactive regex tester: 到目前为止,这是我所拥有的,即使我使用交互式正则表达式测试器对其进行了测试也无法正常工作:

perl -p -i.bak -e 's/#[\s]*label2[\n]#(.*)/${1}/gi;' file.txt

The text file looks like the following 文本文件如下所示

#   label1
#variable=foobar1

#   label2
#variable=foobar2

One option: 一种选择:

perl -0777 -pe 's/(#\s*label2\s*\n)#/$1/s' infile

The -0777 slurps the whole file, parens do grouping over the key line to use it again in the replacement part, and remove what it's outside of it, the # character. -0777抓取整个文件,对它们进行分组以在替换行中再次使用它,并删除其外面的#字符。 It yields: 它产生:

#   label1
#variable=foobar1

#   label2
variable=foobar2

About the debugging, I think it works the same that from a script, use -d switch to activate it. 关于调试,我认为它的工作原理与脚本相同,请使用-d开关将其激活。 Simply put each instruction in a different line to visualize it fine. 只需将每条指令放在不同的行中即可对其进行直观显示。

一个awk解决方案,如果您不仅限于perl:

awk 'f{f=sub(/^#/,"")};/label2/{f=1}1' file.txt

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

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