我有一个input.txt
文件:
Dog walks in the park
Man runs in the park
Man walks in the park
Dog runs in the park
Dog stays still
They run in the park
Woman runs in the park
我希望搜索匹配正则表达式
runs?
的结果并将它们输出到一个文件中,在匹配的两侧添加双星号以标记匹配项。因此,我的期望输出如下:Man **runs** in the park
Dog **runs** in the park
They **run** in the park
Woman **runs** in the park
我希望编写一个函数,作为这个Perl one-liner的包装器(并且还要做一些其他事情),然后使用正则表达式作为它的参数调用它。我编写了以下脚本:
#!/bin/bash
function reg {
perl -ne 's/($1)/**\1**/&&print' input.txt > regfunctionoutput.txt
}
function rega {
regex="$1"
perl -ne 's/($regex)/**\1**/&&print' input.txt > regafunctionoutput.txt
}
perl -ne 's/(runs?)/**\1**/&&print' input.txt > regularoutput.txt
reg 'runs?'
rega 'runs?'
我想要的是第一个Perl单行命令的输出结果。但是,当我尝试将其放入reg
函数并将表达式作为参数传递时,我得到的不是期望的输出结果:
****Dog walks in the park
****Man runs in the park
****Man walks in the park
****Dog runs in the park
****Dog stays still
****They run in the park
****Woman runs in the park
我认为问题是$1
作为函数参数与Perl one-liner中的第一个捕获组之间的冲突。因此,我创建了第二个函数rega
,它首先将该表达式分配给另一个变量,然后再将其传递给Perl。但输出与前一个函数相同。
那么,我如何在函数内部将正则表达式传递给Perl one-liner?我做错了什么?
perl -ne "s/($1)/**\1**/&&print"
) - Aserresed
更高效地完成相同的事情。请参考 simbabque 的答案如何引用它。 - Peter Cordes