我试图找到一些在 sed 中使用的正则表达式,以将模式(可能包含嵌套参数)与一些文本括起来。
一个基本的例子是
length(bill_cycle)
正则表达式应该给出
length(cast(bill_cycle as string))
在这里,我们搜索它以开头length(
,并找到)
与 相关的结尾length(
。然后我们将中间的内容替换bill_cycle
为cast(bill_cycle as string)
即使变量(在本例中为some(somethiing)
)具有嵌套参数,例如
length(some(somethiing))
正则表达式应该给出
length(cast(some(somethiing) as string))
我愿意接受任何 UNIX 脚本或其他可行的命令。非常感谢任何帮助。
答案1
Perl 来救援!
perl -MText::Balanced=extract_bracketed \
-ne 'if (/length(\(.*)/) {
($arg) = (extract_bracketed(($1 =~ /\((.*)\)/)[0]))[1];
print "length(cast($arg as string))\n";
} else { print }' -- input.file > output.file
它使用核心模块文本::平衡从字符串中提取具有平衡分隔符的子字符串。
答案2
使用perl
和递归匹配:
$ cat ip.txt
length(bill_cycle)
length(some(somethiing))
$ perl -pe 's/length(\(((?:[^()]++|(?1))++)\))/length(cast($2 as string))/' ip.txt
length(cast(bill_cycle as string))
length(cast(some(somethiing) as string))
看https://www.rexegg.com/regex-recursion.html了解递归是如何工作的。
答案3
这是一个 awk 脚本,它不使用括号的模式匹配,但对它们进行计数。它还将匹配每行多次出现的情况。
BEGIN {
p = "length"
}
{
row = $0
while (row ~ p"\\(") {
# get the substring from pattern to the end of the line
# and split to array with closing parenthesis separator
x = substr(row, index(row,p) + length(p))
split(x, a, ")")
res = p
# loop for array items and append them to substring
# until we have a string with same number of
# opening and closing parentheses.
for (i=1;i<=length(a);i++) {
res = res a[i] (i==length(a)? "": ")")
if (gsub(/\(/,"(",res) == gsub(/\)/,")",res)) {
print res
break
}
}
# will test again the rest of the row
row = substr(x, length(p))
}
}
一些基本测试
> cat file
some text length(a(b)) testing another occurence length(a))
function(length(c(d(e(f(1), 2)))) testinglength(x)
x length(y))
x length(((y))
length(length(1))
> awk -f tst.awk file
length(a(b))
length(a)
length(c(d(e(f(1), 2))))
length(x)
length(y)
length(length(1))