简体   繁体   English

如何在bash命令行中的perl搜索和替换中引用匹配的模式?

[英]How to refer to the matched pattern in perl search and replace from bash command line?

I want to do search and replace(foo to foobar) with bash using perl command: 我想使用perl命令用bash搜索和替换(foo到foobar):

sudo perl -0777 -i -pe s/'foo'/'foobar'/gs a.txt

but I don't always know what is 'foo', so I want a variable kind of thing which stores the matched pattern. 但是我并不总是知道什么是“ foo”,因此我想要一种可变的东西来存储匹配的模式。

Also can I get a substring of the matched pattern? 还可以获取匹配模式的子字符串吗? Like 'foo' is replaced with 'oobar'(foo becomes oo)? 像“ foo”被替换为“ oobar”(foo变成oo)?

使用表达式评估修饰符e

perl -0777 -i -pe's/(foo)/substr($1, 1) . "bar"/egs' a.txt

$& refers to the entire matched pattern and instead of taking substring of that I used negative lookbehind (?<!u) this means any character other than u : $&指的是整个匹配的模式,而不是我使用否定的lookbehind (?<!u)子字符串,这意味着除u以外的任何字符:

sudo perl -i -0777 -pe s/(?<!u)'oo'/'u$&'/gs

This will match not only any foo but any occurrence of oo but never uoo and replace it with uoobar . 这不仅会匹配任何foo而且会匹配任何出现的oo但永远不会uoo ,并将其替换为uoobar

In the example you gave, you don't need to use the matched text. 在您给出的示例中,您无需使用匹配的文本。

perl -pe's/foo\K/bar/g'

In the scenario you described, you don't need to use the matched text. 在您描述的场景中,您不需要使用匹配的文本。

perl -pe's/f\Koo/oobar/g'

That said, $& contains the matched text. 也就是说, $&包含匹配的文本。

perl -pe's/foo/$&bar/g'

And $1 contains the text matched by the earliest capture, $2 contains the text matched by the second earliest capture, etc. $1包含与最早的捕获匹配的文本, $2包含与第二个最早的捕获匹配的文本,依此类推。

perl -pe's/(f)oo/$1oobar/g'

And /e can be used to treat the replacement expression as code to execute for each match. 并且/e可以将替换表达式视为要为每个匹配执行的代码。

perl -pe's/foo/ substr($&,0,1)."oobar" /eg'

  • There's no point in using /s since the pattern doesn't contain . 使用/s没有意义,因为该模式不包含. .
  • There's no point in using -0777 since your pattern can't span lines. 使用-0777没有意义,因为您的模式无法跨线。
  • The quotes you used were useless, and it's less noisy to quote the entire program instead of individual sections of it. 您使用的引号是没有用的,并且引用整个程序而不是其中的各个部分会比较麻烦。

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

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