Search code examples
bashcygwinnewlinealphabetical

Bash - how to append a newline after lines starting with the same letter?


I have a file with, let's say, the following lines:

alibi
all
bone
chair
clever
cup
curse
dog
donut

I want to add a newline after the last word that starts with the same letter; that is, I want the output to be:

alibi
all

bone

chair
clever
cup
curse

dog
donut

Is there any way to do it? I'm not an expert so I don't even know where to start for this one. I prefer it to be a one-liner, too.

I'm working in Windows environment Cygwin.


Solution

  • I think I found a one-line awk command that does what I'm looking for:

    awk '{if ( substr ($0, 0, 1) != prev) print "\n"$0; else print $0; prev = substr ($0, 0, 1)}' 
    

    This answer was adapted from a one-liner from http://www.cis.uni-muenchen.de/kurse/pmaier/Korpus/DataIntensiveLinguistics/node40.html.