Find Command – Better Search with Regex or Grep?

findgrep

Of these two ways of searching a file recursively in all the subdirectories, which is faster / better ?

find . -regex ".*/.*abc.*"

or

find . | grep ".*abc.*"

Best Answer

UNIX file name can generally consist of octets (8-bit bytes), except for 0x00 (NULL) and 0x2F (/). Every other octet is valid. This includes such nice things as 0x0A (newline).

Your find example will handle file names with weird characters such as newline correctly.

Your find | grep example will give odd and incorrect results when faced with such a thing (it'll see one file called "line 1\nline 2" as two files).

You can use find -print0 | grep -z (if you're using GNU versions, e.g., on Linux); that'll preserve correctness. It'll use a little more memory. Note that you can tell find to use extended regular expressions (for example) using the -regextype option.

If you want to do some really complicated matching, you may like the find2perl script, which will convert a find command line in to a short perl program you can then edit to add in the complexity.