我有以下文件下面包含15
乘以字符串.dog
。通常当我想要在字符串上附加任何数字进行计数时,我使用awk '/.dog/{sub(".dog",++count"&")} 1'
,并且还使用该命令的一些变体几次,如在这个问题中awk sub ++计数每4次匹配,而不是每1次匹配。
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
-house
[.cat]
-kitchen
[.dog]
现在我必须做不同的事情,这样一个唯一的第n个数字被附加到第n个匹配,也就是说,每个第n个数字(1,2,3,等等)被重复,直到第n个匹配h。假设我想让.dog
作为我的模式,并且在.dog
的n次匹配之前,awk.. gsub.. count
命令重复1,同时附加一个数字。所以我的输出应该是:
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
我一直在寻找解决方案,但我没有找到,我相信再次可以找到这个解决方案操纵和适应awk '/.dog/{sub(".dog",++count"&")} 1 | <at the every 5 matches> '
,但我仍然不确定。
$ awk '$0=="[.dog]"{ if (++cnt % 5 == 1) idx++; sub(/./,idx".") } 1' file
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
你可以试试这个awk
$ awk 'BEGIN{FS=OFS="["} {split($2,a,".")}/dog/{a[1]=int(dog++/5);$2=a[1]+1"."a[2]}1' input_file
通过将dog
的每个匹配拆分为20%或0.2,这将在一个整数内生成5个匹配,int
抑制浮点小数,因此可能有更好的方法。
$ awk 'BEGIN{FS=OFS="["} {split($2,a,".")}/dog/{a[1]=int(dog++/5);$2=a[1]+1"."a[2]}1' input_file
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[1.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[2.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
-house
[.cat]
-kitchen
[3.dog]
用户@Cyrus的回答:
awk 'BEGIN{ count=1 } /.dog/{ t=count; sub(/..*/,"",t); sub(".dog", t "&"); count+=.2 }1' file