Sorting multiple-line records in alphabetical order using shell

Viewed 110

There is a file which has the following structure:

L. feritas
E. ferity

L. ars
E. art

L. solitudo
E. solitude

L. celeritas
E. celerity

Each line is a field, and a record spans multiple lines, comprising an L. field, an E. field, and a blank line. How can I sort the records by the fields that are tagged L., keeping the multiple-line records intact?

L. ars
E. art

L. celeritas
E. celerity

L. feritas
E. ferity

L. solitudo
E. solitude
1 Answers

The quick way of coming up with something is:

$ cat file | awk 'BEGIN{RS=""; FS="\n"; OFS="|"}{$1=$1}1' \
  | sort | awk 'BEGIN{FS="|";OFS="\n";ORS="\n\n"}{$1=$1}1'

Or you can write it in a single Gnu AWK,

$ awk 'BEGIN{RS=""; ORS="\n\n"; FS=OFS="\n"; PROCINFO["sorted_in"]="@val_str_asc"}
       {a[NR]=$0}END{for(i in a) print a[i]}' file

If you don't want the last line to be empty, you can do the following:

$ cat file | awk 'BEGIN{RS=""; FS="\n"; OFS="|"}{$1=$1}1' \
  | sort | awk 'BEGIN{FS="|";OFS="\n"}{$1=$1}1' | sed '$d'


$ awk 'BEGIN{RS=""; FS=OFS="\n"; PROCINFO["sorted_in"]="@val_str_asc"}
       {a[NR]=$0}END{for(i in a) print a[i] (--NR?"\n":"")}' file
Related