【问题标题】:How to replace all matches with an incrementing number with a prefix string in awk如何在awk中用带有前缀字符串的递增数字替换所有匹配项
【发布时间】:2018-07-12 22:51:34
【问题描述】:

我有一个这样的文本文件:

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

谢谢。

【问题讨论】:

  • 尝试在帖子发布一段时间后始终选择您问题的任何答案作为正确答案,以使主题完整。
  • 您说您似乎无法正常工作的脚本会产生您从发布的示例输入中询问的预期输出。你有什么问题?

标签: shell awk


【解决方案1】:

另一个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.

抑制最后一个更难,而是延迟替换一个并抑制第一个。

【讨论】:

  • 在使用记录分隔符进行搜索的两个示例中,如何抑制在最后一条记录之后打印的最终 x7(在您的示例中为字符串“content.”)?
  • 感谢您的评论,它没有压制。我更新了修复程序。
【解决方案2】:

awk 保存在这里:

awk '{for(i=1;i<=NF;i++){if($i~/A+/){val="x"++count;sub(/A+/,val,$i)}}} 1' Input_file

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.

【讨论】:

    【解决方案3】:

    最短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.
    

    【讨论】:

      猜你喜欢
      • 2020-06-23
      • 1970-01-01
      • 2011-08-29
      • 2022-06-10
      • 2016-09-26
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多