Finding Files with find and xargs
Locate files by name or pattern, then act on all of them at once.
On this page4 sections
ls only shows you what is in one directory. When you need to search an entire tree - "every .log file anywhere under /var" - that is a job for find.
find: searching by name
find /var -name "*.log" # every .log file under /var, at any depth
find . -name "*.txt" # every .txt file under the current directory
find prints one path per line, which makes it perfect for feeding into another command.
xargs: turning a list into a command
Piping a list of paths into a command like rm does not work directly, because rm expects paths as arguments, not as piped-in text. xargs bridges that gap: it reads whitespace-separated tokens from stdin and runs a command once for each one, appending the token as an argument.
find /var -name "*.log" | xargs rm # delete every match
find . -name "*.tmp" | xargs cat # print the contents of every match
This "find it, then xargs it" pattern is one of the most useful idioms in the entire command line - it turns a search into a bulk operation with almost no code.
Try it
mkdir -p /var/log/app
echo "boot ok" > /var/log/app/one.log
echo "boot ok" > /var/log/app/two.log
find /var -name "*.log"
find /var -name "*.log" | xargs rm
find /var -name "*.log"
The list is empty on the last line - every match was deleted in one step.
Further reading
- "The Linux Command Line" by William Shotts (No Starch Press) - its chapter on finding files walks through
find's many test expressions (by size, by age, by permissions) well beyond-name. - "UNIX and Linux System Administration Handbook" by Nemeth, Snyder, Hein, Whaley, and Mackin (Pearson) - shows this exact
find | xargsidiom used for real sysadmin cleanup and auditing tasks.
Challenge
Find every .log file under /var and delete them all in one command, using find piped into xargs.
Want to experiment first? Try things in the practice terminal (opens in a new tab), then enter the command that solves the task here.
Quiz
Lock in the concepts. Score at least 80% to mark the lesson complete.
Done with this one?
Skipped the challenge? You can mark the lesson complete by hand.