我在 foo.txt 中有以下几行
aaa:6600 location: US
aaa:6622 location: US
xxx:6601 location: EU
xxx:6602 location: EU
xxx:6603 location: EU
ggg:7701 location: KR
ggg:8808 location: KR
我想将所有开始相同的聚集进行分组,并在它们之间添加一个新行,因此最终输出如下所示
aaa:6600 location: US
aaa:6622 location: US
xxx:6601 location: EU
xxx:6602 location: EU
xxx:6603 location: EU
ggg:7701 location: KR
ggg:8808 location: KR
答案1
awk -F: '/^$/{next}$1!=f&&NR>1{print ""}{f=$1;print;}' foo.txt
给出
aaa:6600 location: US
aaa:6622 location: US
xxx:6601 location: EU
xxx:6602 location: EU
xxx:6603 location: EU
ggg:7701 location: KR
ggg:8808 location: KR
关于样本数据。
解释。
所述-F:
字段将由冒号分隔。/^$/{next}
表示跳过输入中的所有空白行。$1!=f&&NR>1{print ""}
如果当前名称与保存的名称不同f
且文件中的行号大于1,则打印一个空行以开始一个新组。{f=$1;print}
对于所有行,保存名称f
并打印该行。有很多方法可以使它更短,但对我来说,这只需要基本的awk
。
答案2
$ awk -F':' '!NF{next} $1 != prev{if (NR>1) print ""; prev=$1} 1' file
aaa:6600 location: US
aaa:6622 location: US
xxx:6601 location: EU
xxx:6602 location: EU
xxx:6603 location: EU
ggg:7701 location: KR
ggg:8808 location: KR