linux find


Write this up as a response to someone on hackernews but didn’t submit it. Dumping here for reference…


search for exact pattern in all basenames

find . -name "<pattern>"

search for pattern at the start of basenames

find . -name "<pattern>*"

search for pattern at the end of basenames

find . -name "*<pattern>"

search for pattern anywhere in the basename

find . -name "*<pattern>*"

search for multiple patterns anywhere in the basename

find . -name "*<p1>*<p2>*"

path based patterns (same wildcards as above)

find . -path "*<p1>/*/<p2>*"

directories using basenames

find . -type d -name -f "*<pattern>*"

non directories using basenames (technically directories are files too!)

find . -type f -name -f "*<pattern>*"

only recurse 3 directories deep

find . -maxdepth 3 -name "*<pattern>*"

start 2 directories deep

find . -maxdepth 2 -name "*<pattern>*"

search only in directories 2 levels deep

find . -maxdepth 2 -mindepth 2 -name "*<pattern>*"

execute a command on each result (force remove files)

find . -type f -name "*<pattern>*" -exec rm -f {} \;

execute two commands in order on each result

find . -type f -name "*<pattern>*" -exec cp -f {} ./archive/ \; -exec rm -f {} \;

use find results with GNU parallel to speed up smaller tasks

(so long as they’re safe in parallel that is)

find . -name "*<pattern>*" | parallel ./some-script.sh {}