简体   繁体   中英

Perl multiline search replace

I want to find and corresponding block and uncomment the second line in text file using 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. 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. Simply put each instruction in a different line to visualize it fine.

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

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

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