input.txt文件
12345678,Manoj,23,Developer
12345678,Manoj,34,Developer
12345678,Manoj,67,Developer
12345679,Vijay,12,Tester
12345679,Vijay,98,Tester
12345676,Samrat,100,Manager
12345676,Samrat,25,Manager
12345676,Samrat,28,Manager
Run Code Online (Sandbox Code Playgroud)
期望的输出文件
12345678,Manoj,23,Developer,0
12345678,Manoj,34,Developer,1
12345678,Manoj,67,Developer,2
12345679,Vijay,12,Tester,0
12345679,Vijay,98,Tester,1
12345676,Samrat,100,Manager,0
12345676,Samrat,25,Manager,1
12345676,Samrat,28,Manager,2
Run Code Online (Sandbox Code Playgroud)
说明
这里第一个值,即12345678在我的输入文件的前3行中是相同的,所以分别附加前3行0 ,1 and ,2.和以下几行类似.
如何在Shell脚本中完成.
在期望的输出中编辑
是否也可以将所需输出数字格式更改为以下输出?
12345678,Manoj,23,Developer,0000000
12345678,Manoj,34,Developer,0000001
12345678,Manoj,67,Developer,0000002
12345679,Vijay,12,Tester,0000000
12345679,Vijay,98,Tester,0000001
12345676,Samrat,100,Manager,0000000
12345676,Samrat,25,Manager,0000001
12345676,Samrat,28,Manager,0000002
Run Code Online (Sandbox Code Playgroud)
新: 是否有可能从0000019开始编号.是否有任何其他选项来初始化变量,如a = 5,a = 19,a = 39,之后我可以增加.
12345678,Manoj,23,Developer,0000019
12345678,Manoj,34,Developer,0000020
12345678,Manoj,67,Developer,0000021
12345679,Vijay,12,Tester,0000019
12345679,Vijay,98,Tester,0000020
12345676,Samrat,100,Manager,0000019
12345676,Samrat,25,Manager,0000020
12345676,Samrat,28,Manager,0000021
Run Code Online (Sandbox Code Playgroud)
使用awk:
$ awk 'BEGIN{FS=OFS=",";RS="\r?\n"}{print $0,a[$1]++}' file
Run Code Online (Sandbox Code Playgroud)
输出:
12345678,Manoj,23,Developer,0
12345678,Manoj,34,Developer,1
12345678,Manoj,67,Developer,2
12345679,Vijay,12,Tester,0
12345679,Vijay,98,Tester,1
12345676,Samrat,100,Manager,0
12345676,Samrat,25,Manager,1
12345676,Samrat,28,Manager,2
Run Code Online (Sandbox Code Playgroud)
编辑:
随着要求的变化和许多评论的发生,这里是最终版本(修订版一,因为要求在评论和OP中有所不同,敲响了木材):
$ awk 'BEGIN{FS=","}{sub(/\r$/,"");printf "%s,%07d" ORS,$0,a[$1]++}' file
Run Code Online (Sandbox Code Playgroud)
解释:
$ awk '
BEGIN {
FS=","
# ORS="\r\n" # uncomment if Windows line-endings are desired
}
{
sub(/\r$/,"") # remove Windows line-endings (ie. \r from \r\n)
printf "%s,%07d" ORS,$0,a[$1]++ # output zeropadded running count on $1
}' file
Run Code Online (Sandbox Code Playgroud)
用gawk,mawk,busybox awk和原始awk(awk版本20121220)测试.哦,5年前回收了我的Solaris盒子.; d