Regex zum Gruppieren mit gleichem Namen

Regex zum Gruppieren mit gleichem Namen

Ich habe folgende Zeilen in 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

Ich möchte alle Gruppen mit der gleichen Startgruppe bilden und eine neue Zeile zwischen ihnen einfügen, sodass die endgültige Ausgabe wie folgt aussieht

    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

Antwort1

awk -F: '/^$/{next}$1!=f&&NR>1{print ""}{f=$1;print;}' foo.txt

gibt

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

auf den Beispieldaten.

Erläuterung.

Die -F:Felder werden durch Doppelpunkte getrennt. /^$/{next}Alle leeren Zeilen in der Eingabe werden übersprungen. $1!=f&&NR>1{print ""}Wenn der aktuelle Name nicht mit dem gespeicherten Namen übereinstimmt fund die Zeilennummer in der Datei größer als 1 ist, wird eine leere Zeile gedruckt, um eine neue Gruppe zu beginnen. {f=$1;print}Für alle Zeilen wird der Name gespeichert fund die Zeile wird gedruckt. Es gibt Möglichkeiten, die Eingabe zu verkürzen, aber für mich ist dafür nichts weiter als die Grundkenntnisse erforderlich awk.

Antwort2

$ 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

verwandte Informationen