gpt4 book ai didi

regex - 如何将正则表达式作为参数传递给 Bash 脚本中的 Perl 单行代码?

转载 作者:行者123 更新时间:2023-11-29 09:11:56 25 4
gpt4 key购买 nike

我有这个 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 单行程序的包装器(它会做一些其他事情),然后用正则表达式作为参数调用它。我写了以下脚本:

#!/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 单行代码中的第一个捕获组之间存在一些冲突。所以我创建了第二个函数,rega,它首先将该表达式分配给一个不同的变量,然后才将其传递给 Perl。但输出与之前的函数相同。

那么,如何将正则表达式传递给函数内的 Perl 单行代码?我做错了什么?

最佳答案

您需要使用双引号 " 因为 shell 不会在单引号中插入变量 '。这也很好地解释了在 this answer 中。

function reg {
perl -ne "s/($1)/**\$1**/g&&print" input.pl > regfunctionoutput.txt
}

此外,在 Perl 中,正则表达式捕获组以 $1$2 等结尾。不在 \1 中。如果您打开警告(在单行代码中使用 -w),您将得到一个 \1 更好地写为 $1 警告。在 perldiag 中有解释.

\%d better written as $%d

(W syntax) Outside of patterns, backreferences live on as variables. The use of backslashes is grandfathered on the right-hand side of a substitution, but stylistically it's better to use the variable form because other Perl programmers will expect it, and it works better if there are more than 9 backreferences.

(W syntax) 意味着您可以使用 no warnings 'syntax';

关闭此警告

关于regex - 如何将正则表达式作为参数传递给 Bash 脚本中的 Perl 单行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com