Skip to content
Intermediate LinuxLesson 9 of 27 2 min read

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

bash
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.

bash
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

Run these in the practice terminal (opens in a new tab). It opens in a new tab, so you keep your place here.
bash
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 | xargs idiom 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.

0 of 2 answered

Done with this one?

Skipped the challenge? You can mark the lesson complete by hand.

Your notes

Kept on this browser only.