Sorting a specific column!

What im trying to do is sort the output by the number on the second column and than limit the result to only the first three lines.

This is the code

idlist="x23s52; f34233; 2343xs; 25x34; si342d"
cntr=1
idcnt=$(print $nidlist |tr ';' '\n' |wc -l)
numofgrps=0
while (($cntr <= $idcnt))
do
    idlist=$idlist\;
    numofgrps=$numofgrps\;
    currid=$(print $idlist |awk -F ';' '{print  $1}')
    numofgrps=`cat /home/n5ddc8/BI_Ab_Intito_dist/BI_Ab_Initio_dist.report.dat | grep $currnid | wc -l`
    currcnt="$currid$numofgrps \n"
    toplst=$toplst   $currcnt
    idlist=${idlist#*\;}
    cntr=$(($cntr + 1))
done
print $toplst
 

The output of this code looks something like this.

x23s52   3
f34233   2
21jh43   1
ad34nj   5

Ascending

output | sort -k2 -n | head -n3

Descending

output | sort -k2 -rn | head -n3

Take a look at this:

numofgrps=`cat /home/n5ddc8/BI_Ab_Intito_dist/BI_Ab_Initio_dist.report.dat | grep $currnid | wc -l`

We can remove cat since grep can read from file.

grep $currnid /home/n5ddc8/BI_Ab_Intito_dist/BI_AB_Initio_dist.report.dat | wc -l

But also, grep can do the line count that wc -l does

grep -c $currnid /home/n5ddc8/BI_Ab_Intito_dist/BI_AB_Initio_dist.report.dat

By leveraging the functionality of just one program your code is more efficient.

See if you can do the same in other areas.

And grep -c is even more portable, because wc -l has leading spaces on *some* OS.
Likewise grep -c ^ file is perhaps less readable but portable, compared to wc -l < file .

On top of several syntactical/orthographical errors ($nidlist, $currnid, ), the entire script is way too complicated. Unless there are requirements or conditions not shown, a for loop would handle the situation much better:

for currid in "$idlist"
  do printf "%s  %d"  $currid $(grep -c $currid path/to/file)
  done | sort -k2 | head -n3

This would have the drawback that it grep s through the file n times. Doing the whole thing in e.g. awk could reduce that resource consumption by far.

---------- Post updated at 22:11 ---------- Previous update was at 21:55 ----------

Would this (as a first step, and assuming NO spaces in idlist) satisfy your needs:

grep -Eo "${idlist//;/|}" file | sort | uniq -c
     5 f34233
     6 x23s52

?