home / blog

Power of find

I’ve noticed a lot of people seem to struggle with the *NIX find command, which isn’t the most intuitive thing to use. Here are some examples.

The general strategy is use one or more predicates such as -name for matching filename/filename case insensitive, -size for file size, -regex/-iregex etc. Many predicates implies AND, OR can be forced using -or switch. Searches can be narrowed using -maxdepth and -mindepth. Results can be either printed as default (-print) or used in commands (-exec). That’s about it.

# find cpp files
find . -name "*.cpp"

# find anything with a given substring
find . -iname "*foo*"

# find files bigger than 50meg
find . -size +50M

# delete files bigger than 50meg
find . size +50M -exec rm -f "{}" \;

# delete files bigger than 50meg or containing "horse" in their name
find . size +50M -or -iname "*horse*" -exec rm -f "{}" \;

# find files bigger than 50meg only in current directory
find . size +50M -maxdepth 1

# find files bigger than 50meg only in only next directory
find . size +50M -mindepth 2 -maxdepth 2 

# find filenames only consisting of numbers (regex)
find . -regex '.*/[0-9]+$'

# find files modified in last 21 days
find . -mtime -21

# find files older than 7 days
find . -mtime +7

# find from multiple directories java or properties
find ./foo ./bar -iname "*.java" -or -iname "*.properties"

This entry was posted in geek and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.