我在 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