listing by size in Unix

Discussion in 'Mac Programming' started by dougphd, Jun 5, 2016.

  1. dougphd macrumors member

    Joined:
    Apr 28, 2016
    #1
    Am I in the right forum?

    wc -l * gives me the number of lines in each file in the directory but does not sort them. ls -l -S sorts by the number of bytes. How to I get the files sorted by the number of lines. Thanks
     
  2. dotnet macrumors 6502a

    dotnet

    Joined:
    Apr 10, 2015
    Location:
    Sydney, Australia
    #2
    Well, ls doesn't sort by lines because files don't usually have lines, only text files do. But to answer your question:

    wc -l *|sort -n

    should do what you want.
     
  3. dougphd thread starter macrumors member

    Joined:
    Apr 28, 2016
    #3
    Thanks that worked. I looked at the man pages for sort. The explanation for -n (compare according to string numerical value) isn't clear. What is the string numerical value?
     
  4. mfram, Jun 6, 2016
    Last edited: Jun 6, 2016

    mfram macrumors 65816

    Joined:
    Jan 23, 2010
    Location:
    San Diego, CA USA
    #4
    Sorting strings that contain numbers might not get the result you expect because sorting numeric strings of differing lengths in lexical order don't come out the same as numeric order. Length is irrelevant in lexical order but matters in numeric order.

    Like this:

    Code:
    mbp:~$ cat test.txt
    2
    100
    11
    200
    1
    21
    mbp:~$ sort test.txt
    1
    100
    11
    2
    200
    21
    mbp:~$ sort -n test.txt
    1
    2
    11
    21
    100
    200
    
     
  5. hughm123 macrumors newbie

    Joined:
    Dec 3, 2014
    #5
    The POSIX (http://www.unix.com/man-page/posix/1p/sort/) and Solaris man pages are clearer:

    -n Restrict the sort key to an initial numeric string, consisting of optional
    <blank> characters, optional minus-sign, and zero or more digits with an
    optional radix character and thousands separators (as defined in the current
    locale), which shall be sorted by arithmetic value. An empty digit string shall
    be treated as zero. Leading zeros and signs on zeros shall not affect ordering.

    -r Reverse the sense of comparisons.

    So it's treated as a leading number, possibly with non-numeric content afterwards.

    I often use "sort -nr" to get a reverse sort, largest first.
     
  6. dougphd thread starter macrumors member

    Joined:
    Apr 28, 2016
    #6
    Thanks guys. One more piece of knowledge into a list that is all too short.
     
  7. dotnet macrumors 6502a

    dotnet

    Joined:
    Apr 10, 2015
    Location:
    Sydney, Australia
    #7
    Fortuitously, wc aligns its numeric output on the decimal point, so -n isn't even needed. However, not all utilities do, so it's safer to get into the habit of using -n whenever you want to sort in numeric order.
     

Share This Page