Abhishek Baranwal
Abhishek Baranwal

Reputation: 62

sorting in unix by file size

I have a unix file with data like:

35|ag
0|ca
22.0 K|nt
43.8 G|ct
90.0 M|se
2.4 M|ew
1.6 K|et
0|er
0|dr
18|ld

Output:

43.8 G|ct   
90.0 M|se
2.4 M|ew    
22.0 K|nt
1.6 K|et
35|ag
18|ld
0|ca
0|er
0|dr

I need to sort this in decreasing order of size. I could convert this to uniform size such as bytes and then sort them, but I was hoping if it could be sorted directly.

Thanks in advance!

Upvotes: 1

Views: 142

Answers (1)

James Brown
James Brown

Reputation: 37404

Using GNU sort. man sort:

   -h, --human-numeric-sort
          compare human readable numbers (e.g., 2K 1G)

but we need to remove the spaces from the first field. Using tr

$ cat file | tr -d ' ' | sort -h -r -t\| -k 1
43.8G|ct
90.0M|se
2.4M|ew
22.0K|nt
1.6K|et
35|ag
18|ld
0|er
0|dr
0|ca

Upvotes: 1

Related Questions