Bash Tutorial · Pipes and Text Processing · Lesson 13 of 30
Bash find and xargs
Find files by name, type, size and age, and run commands on them safely with -exec and xargs.
find
find PATH CONDITIONS ACTIONS:
-name '*.log'(quote the pattern!),-inamecase-insensitive-type ffiles,-type ddirectories-size +10M,-mtime -7(modified in the last 7 days)- actions:
-print(default),-delete,-exec cmd {} +
mkdir -p app/logs app/src
touch app/logs/a.log app/logs/b.log app/src/main.sh app/README.md
find app -name '*.log' | sort
find app -type d | sort
find app -name '*.log' -exec wc -c {} + | tail -n 1
Output
app/logs/a.log app/logs/b.log app app/logs app/src 0 total
Run this on your computer — see “Get Started” for setup.
xargs
xargs turns input lines into command arguments. File names can contain spaces, so pair find -print0 with
xargs -0:
mkdir docs
touch "docs/meeting notes.txt" docs/plan.txt
find docs -name '*.txt' -print0 | xargs -0 ls | sort
find docs -name '*.txt' -print0 | xargs -0 -I{} echo "processing: {}" | sort
Output
docs/meeting notes.txt docs/plan.txt processing: docs/meeting notes.txt processing: docs/plan.txt
Run this on your computer — see “Get Started” for setup.
Test yourself
Why use find -print0 | xargs -0?
It's fasterSo file names with spaces or newlines are handled correctlyTo include hidden filesTo run commands in parallel
Show answer
Answer: So file names with spaces or newlines are handled correctly