_           _                 
 | |_ ___  __| |____  ___ _   _ 
 | __/ _ \/ _` |_  / / _ \ | | |
 | ||  __/ (_| |/ / |  __/ |_| |
  \__\___|\__,_/___(_)___|\__,_|

Sort fields on each line using AWK

Given data similar to the example shown below, the objective is to

Example input:

one,two,three,Numbers,
dog,CAT,parrot,ANIMALS,
flea,fly,butterflu, Insects,
Pots,Pans,Brushes,household ,
three,two,one,Numbers,
cat,dog,parrot,ANIMALS ,
red,blue,green,Colours,

Example output:

Numbers,one,three,two
ANIMALS,cat,dog,parrot
Insects,butterflu,flea,fly
household,brushes,pans,pots
Numbers,one,three,two
ANIMALS,cat,dog,parrot
Colours,blue,green,red

AWK script

The following AWK script performs the required transformation. I saved it as namesort.awk.

BEGIN { FS = "[ ]*,[ ]*" }

{
    split($0, a);
    delete a[4];
    delete a[5];
    for (x in a) a[x] = tolower(a[x]);
    asort(a);
    print $4 "," a[1] ","  a[2] "," a[3];
}

Notes

To add a comma to the end of every line in Vim:

:%s/$/,/

To use the above AWK script in VIM, run it using the following command:

:%!awk -f namesort.awk

To sort the processed output in Vim:

:%!sort

Example output:

ANIMALS,cat,dog,parrot
ANIMALS,cat,dog,parrot
Colours,blue,green,red
household,brushes,pans,pots
Insects,butterflu,flea,fly
Numbers,one,three,two
Numbers,one,three,two

To count duplicates or each unique line:

:%!uniq -c

Example output:

      2 ANIMALS,cat,dog,parrot
      1 Colours,blue,green,red
      1 household,brushes,pans,pots
      1 Insects,butterflu,flea,fly
      2 Numbers,one,three,two