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.

Create a free account to save this page, take notes and track your progress. Sign in

find

find PATH CONDITIONS ACTIONS:

  • -name '*.log' (quote the pattern!), -iname case-insensitive
  • -type f files, -type d directories
  • -size +10M, -mtime -7 (modified in the last 7 days)
  • actions: -print (default), -delete, -exec cmd {} +
Finding files
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:

Safe xargs with spaces in names
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?

  1. It's faster
  2. So file names with spaces or newlines are handled correctly
  3. To include hidden files
  4. To run commands in parallel
Show answer

Answer: So file names with spaces or newlines are handled correctly

Was this page helpful?