Linux and Bash course menu
Linux find Command with Examples
Find files by name, type, size and age with the find command, run actions with -exec and -delete, handle file names safely with xargs -0, and use locate.
On this page
grep searches inside files. find searches for the files themselves, by name, type, size, age and more.
The form is find where conditions:
find appapp
app/logs
app/logs/small.log
app/logs/big.log
app/README.md
app/build
app/build/empty.tmp
app/src
app/src/util.py
app/src/main.pyBy name#
find app -name "*.py"
find app -iname "readme*"app/src/util.py
app/src/main.py
app/README.md-iname ignores case. Always quote the pattern, so that the shell does not expand it first.
By type#
-type f finds files, and -type d finds folders:
find app -type dapp
app/logs
app/build
app/srcBy size and age#
find app -type f -size +1M
find app -type f -mtime +30
find app -type f -emptyapp/logs/big.log
app/logs/small.log
app/build/empty.tmpCombining conditions#
Conditions are joined with "and" by default. Use -o for "or", and ! for "not":
find app -type f \( -name "*.log" -o -name "*.tmp" \)
find app -type f ! -name "*.py" -path "*src*"
find app -maxdepth 1 -type fapp/logs/small.log
app/logs/big.log
app/build/empty.tmp
app/README.mdDo something with the results#
-exec runs a command on each match. {} stands for the file, and \; ends the command:
find app -name "*.py" -exec wc -l {} \;1 app/src/util.py
1 app/src/main.pyEnding with + passes many files to one command, which is faster:
find app -name "*.py" -exec wc -l {} +1 app/src/util.py
1 app/src/main.py
2 totalTo delete, use -delete. Always run without it first, to see what would be removed:
find app -name "*.tmp"
find app -name "*.tmp" -delete
find app -name "*.tmp" | wc -lapp/build/empty.tmp
0find with xargs#
File names can contain spaces. -print0 and xargs -0 separate names with a null character, so they are always safe:
touch "app/src/my notes.txt"
find app -name "*.txt" -print0 | xargs -0 ls -l-rw-rw-r-- 1 asha asha 0 Nov 5 06:24 app/src/my notes.txtHide permission errors#
Searching the whole system prints many "Permission denied" lines. Discard them:
find / -name "hostname" -type f 2> /dev/null | head -n 2/usr/bin/hostname
/usr/lib/byobu/hostnamelocate#
locate searches a prebuilt database, so it is very fast, but it may be out of date. Install it with sudo apt install plocate, and update it with sudo updatedb.
Common mistakes#
Practice#
Practice exercise
Print only the names of the two largest files under app, with their sizes in bytes.
Show hint
find -printf '%s %p\n' prints size and path. Then use sort -nr and head.
Show solution
find app -type f -printf '%s %p\n' | sort -nr | head -n 22000000 app/logs/big.log
2 app/src/util.pyKey takeaway#
Next: sort, uniq, cut, tr and wc.
Finished this lesson?