简体   繁体   中英

Bash: How to sort files in a directory by number of lines?

I'm new to bash so my knowledge is pretty limited, especially when it comes to writing scripts. Is there any way in which a script can read into the directories it is given and sort the files inside in descending order, from the one with most lines to the one with least?

find /some/dir -type f -print0 | wc -l --files0-from=- | sort -n -r

Should do what you want

the find program scans directory /some/dir recursively, outputs the full path for each file it finds ( -type f means file as in not a directory/socket/etc). the output list uses nul-terminated strings ( -print0 ) in order to safely deal with dodgy filenames.

That list of filenames feeds into wc (wordcount) which uses ( --files0-from=- ) to expect a nul-terminated filelist as input, and for each file it prints the number of lines ( -l ) in front of the filename.

That list in turn, feeds into sort which sorts the list in reverse ( -r ) numeric ( -n ) fashion; and since the linecount is in front of the filenames, that means the longest file (most lines) is on top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM