IntermediateLesson 9 of 15
find, xargs & Bulk File Processing – Bash
Find files by name, age and size and apply commands to them.
find searches directory trees based on criteria. Syntax: find <start folder> <tests> <action>. Without an action, the path is printed.
find . -name "*.log" # by name (quote patterns!)
find . -type f -mtime +30 # files older than 30 days
find . -type d -name node_modules -prune -o -type f -name "*.js" -print # skip a folder
find /var/log -type f -size +100M # larger than 100 MB
find . -maxdepth 1 -type f -newer referenz.txtWith -exec you run a command per match ({} is the placeholder, \; ends the command; with + many files are bundled per call). Alternatively you pass the list to xargs. For file names with spaces, -print0 and xargs -0 are mandatory.
find . -name "*.tmp" -exec rm {} + # delete matches in bundles
find . -name "*.log" -mtime +7 -delete # shorter, with -delete
find . -name "*.md" -print0 | xargs -0 wc -l # safe with spaces
find . -name "*.jpg" -print0 | xargs -0 -n 1 -P 4 gzip # 4 processes in parallel, 1 file each
ls *.txt | xargs -I {} cp {} backup/{} # -I: freely chosen placeholderExample: rename all files with a given extension. The preliminary test with echo (dry run) is worth its weight in gold.
for f in *.jpeg; do
[[ -e "$f" ]] || continue
neu="${f%.jpeg}.jpg" # cut off the suffix, append the new one
echo mv -- "$f" "$neu" # dry run: only display; remove "echo" later
doneWarningWith
find, always put the conditions before -delete and test without it first. Order matters: find . -delete -name "*.log" deletes everything! And quote "*.log", otherwise the shell expands the pattern before find even sees it.TipIf you only search by name,
fd (modern) or ls **/*.log (after shopt -s globstar) are shorter. But find is installed everywhere and is therefore the safe tool for scripts.