用递增数字替换字符串的正则表达式
Regex for Replacing String with Incrementing Number
曾几何时,我使用 UltraEdit 制作了这个
text 1
text 2
text 3
text 4
...
从那个
text REPLACE
text REPLACE
text REPLACE
text REPLACE
...
就像用 \i
替换 REPLACE
一样简单
现在,我该如何使用 eg 来做到这一点。 sed
?
如果您提供了解决方案,能否添加用前导零填充结果的说明?
谢谢
您可以为此使用 awk 而不是 sed:
awk '{ sub(/REPLACE/, ++i) } 1' file
text 1
text 2
text 3
text 4
...
这是你想要的吗?
$ awk '{$NF=sprintf("%05d",++i)} 1' file
text 00001
text 00002
text 00003
text 00004
如果不是,请编辑您的问题以显示一些更具代表性的示例输入和预期输出(如果 ...
确实不存在于您的输入和输出中,请删除它们,因为它们使您的例如不可测试)。
perl -i -pe 's/REPLACE/++$i/ge' file
对于最小宽度的零填充(即如果有 10 个替换,使用字段宽度 2):
perl -i -pe '
BEGIN {
$patt = "REPLACE";
chomp( $n = qx(grep -co "$patt" file) );
$n = int( log($n)/log(10) ) + 1;
}
s/$patt/ sprintf("%0*d", $n, ++$i) /ge
' file
曾几何时,我使用 UltraEdit 制作了这个
text 1
text 2
text 3
text 4
...
从那个
text REPLACE
text REPLACE
text REPLACE
text REPLACE
...
就像用 \i
REPLACE
一样简单
现在,我该如何使用 eg 来做到这一点。 sed
?
如果您提供了解决方案,能否添加用前导零填充结果的说明?
谢谢
您可以为此使用 awk 而不是 sed:
awk '{ sub(/REPLACE/, ++i) } 1' file
text 1
text 2
text 3
text 4
...
这是你想要的吗?
$ awk '{$NF=sprintf("%05d",++i)} 1' file
text 00001
text 00002
text 00003
text 00004
如果不是,请编辑您的问题以显示一些更具代表性的示例输入和预期输出(如果 ...
确实不存在于您的输入和输出中,请删除它们,因为它们使您的例如不可测试)。
perl -i -pe 's/REPLACE/++$i/ge' file
对于最小宽度的零填充(即如果有 10 个替换,使用字段宽度 2):
perl -i -pe '
BEGIN {
$patt = "REPLACE";
chomp( $n = qx(grep -co "$patt" file) );
$n = int( log($n)/log(10) ) + 1;
}
s/$patt/ sprintf("%0*d", $n, ++$i) /ge
' file