Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

dougphd

macrumors member
Original poster
Apr 28, 2016
70
0
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
 

dotnet

macrumors 65816
Apr 10, 2015
1,304
992
Sydney, Australia
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.
 

dougphd

macrumors member
Original poster
Apr 28, 2016
70
0
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?
 

mfram

Contributor
Jan 23, 2010
1,223
289
San Diego, CA USA
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
 
Last edited:

hughm123

macrumors newbie
Dec 3, 2014
28
11
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?

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.
 

dougphd

macrumors member
Original poster
Apr 28, 2016
70
0
Thanks guys. One more piece of knowledge into a list that is all too short.
 

dotnet

macrumors 65816
Apr 10, 2015
1,304
992
Sydney, Australia
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.