Sorry, I only know how to write the script for a pre-determined value of n. It looks like $n represents the number of data lines to read before sorting and I don't know how to determine the length of data before reading them.