[英]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'
/s
since the pattern doesn't contain .
/s
没有意义,因为该模式不包含.
. -0777
since your pattern can't span lines. -0777
没有意义,因为您的模式无法跨线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.