Skip to main content

disorder file awk

Randomize a file lines with AWK

The goal here is simple:

  1. I have a file (music playlist, user list,...)
  2. I want to disorder it, just like I woul beat the cards
I asked this a long time ago on Usenet (fr.comp.os.unix), and I got this anwser from Stéphane CHAZELAS.

If the file is not too big:

awk < fichier '{a[n++]=$0}
                  END{for(srand();n--;a[i]=b)
                      {b=a[n];a[n]=a[i=int(rand()*NR)]};
                      while(++n<NR)print a[n]}'

Otherwise:

awk < fichier 'BEGIN{srand()}{print rand(),$0}'  | sort -k1,1 | cut -d  -f2-

I write it down here just for the archives