Awk

正則表達式將它們分組相同的名稱

  • March 18, 2020

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

關於樣本數據。

解釋。

say-F:欄位將由冒號分隔。/^$/{next}表示跳過輸入中的所有空行。$1!=f&&NR>1{print ""}如果目前名稱與保存的東西不同,f並且文件中的行號大於1,則列印一個空行以開始一個新組。{f=$1;print}對於所有行,保存名稱f並列印該行。有一些方法可以讓它更短,但對我來說,這不需要比 basic 更多的東西awk

引用自:https://unix.stackexchange.com/questions/573401