Group lines according to first word

awkgrepsedtext processing

How can I modify the following content of a file:

cat:persian/young-1
cat:winter/young-2
cat:summer/wild-3
dog:persian/young-1
dog:winter/young-2
dog:summer/wild-3

To :

cat:persian/young-1
cat:winter/young-2
cat:summer/wild-3

dog:persian/young-1
dog:winter/young-2
dog:summer/wild-3

It's not specific to dog or cat, it's more of symbolic representation of whatever the first word/term is

Best Answer

You could do something like:

awk -F: 'NR>1 && $1 "" != last {print ""}; {print; last = $1}'

The "" is to force string comparison. Without it, it wouldn't work properly in input like:

100:foo
100:bar
1e2:baz
1e2:biz

Where 100 and 1e2 would be compared as numbers.

Related Question