Finder/Terminal: Find files that contain less than 21 lines of text

finder

I have lots of text files that have a different number of lines of text in them.

In Mac OS Finder, is there any way to search for files that are less than 21 lines? (i.e. each file has less than 21 line of text in them).

The Search for files gives lots of options, but I can't see one that is for line length.

From reading up on the subject, it seems using Grep in Terminal may be the best way, but I haven't found any sources that explain how to use Grep to search for line length on multiple files.

Best Answer

In Terminal you can combine find and wc for this:

find /path/to/directory -type f \
    -exec bash -c '[[ $(wc -l < "$1") -lt 21 ]]' _ {} \; -print

This will find all files (-type f) beneath /path/to/directory, count the lines (wc -l < "{}", {} gets replaced by any file found) and print the file name for files containing less than 21 lines.

PS: It will also try to count the lines in non-text files. If this causes issues, use the following instead:

find /path/to/directory -type f -exec bash -c 'file -b "$1" | grep -q text' _ {} \; \
    -exec bash -c '[[ $(wc -l < "$1") -lt 21 ]]' _ {} \; -print

PPS: To start from the current directory, replace the path at the beginning with . (a single dot, for the current directory)

PPPS: To restrict the search to the current directory, use find . -maxdepth 1 -type f ...