我有一个像这样的文本文件:
AAAAAA this is some content.
This is AAAAAA some more content AAAAAA. AAAAAA
This is yet AAAAAA some more [AAAAAA] content.
我需要用递增的数字替换所有出现的AAAAAA,例如,输出如下所示:
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
如何将所有匹配项替换为递增的数字和字符串前缀?
我的问题与 How to replace all matches with an incrementing number in BASH?但是我尝试修改的给定解决方案似乎无法正常工作。
awk '{for(x=1;x<=NF;x++)if($x~/AAAAAA/){sub(/AAAAAA/,"x"++i)}}1' file
谢谢。
答案 0 :(得分:3)
另一个awk
$ awk -v w='AAAAAA' '{while($0~w) sub(w,"x"++c)}1' file
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
本质上是效率低下的gsub
。
此人使用记录分隔符作为搜索词
$ awk -v RS='AAAAAA' -v ORS='' 'NR>1 && $0="x"++c $0' file
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
抑制最后一个比较困难,而是推迟替换一个并抑制第一个。
答案 1 :(得分:1)
awk
保存在此处:
awk '{for(i=1;i<=NF;i++){if($i~/A+/){val="x"++count;sub(/A+/,val,$i)}}} 1' Input_file
OR
awk '{for(i=1;i<=NF;i++){if($i~/A+/){sub(/A+/,"x"++count,$i)}}} 1' Input_file
输出如下。
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
答案 2 :(得分:0)
最短的perl
技巧:
perl -pe 's/\bA+\b/x.++$i/ge' file
输出:
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.