What I Wanted to Do
I wanted to search for files with find and then delete or process all of them at once.
Typing find . -name "*.log" | rm didn’t work at all — that’s when I found out about xargs.
Basic xargs Usage
Pass stdin as arguments to a command
echo "file1.txt file2.txt file3.txt" | xargs ls -l
xargs takes stdin and passes each item as arguments to the specified command.
Delete files found by find in bulk
find . -name "*.log" | xargs rm
xargs converts find’s output into arguments for rm.
Handle filenames with spaces (-0 option)
find . -name "*.txt" -print0 | xargs -0 rm
Combine -print0 with -0 to safely handle filenames that contain spaces or newlines.
Limit arguments per command run (-n)
echo "a b c d e" | xargs -n 2 echo
a b
c d
e
-n 2 passes two arguments at a time.
Specify argument position (-I)
ls *.txt | xargs -I{} cp {} /backup/{}
-I{} lets you place the argument anywhere in the command using {}. Handy for copying files into a backup directory.
Run commands in parallel (-P)
find . -name "*.gz" | xargs -P 4 -I{} gzip -d {}
-P 4 runs 4 processes in parallel — a big speedup when processing lots of files.
Common Gotchas
- Piping directly into
rmdoesn’t work — you needxargsin between - Always use
-print0 | xargs -0when filenames may contain spaces or newlines - When using
-I{}, include the full path around{}as needed xargsalso fixes the “Argument list too long” error when you have too many files- There’s no
--dry-runflag — substituteechofirst to preview the commands before running for real
Related Articles
- How to Search Files with grep and find on Linux
- How to Use the sed Command for Text Substitution and Editing in Linux
- How to Extract and Process Text with the awk Command
- Linux Basic Commands Cheatsheet (ls/cd/mkdir/rm)
- How to Sync and Backup Files with rsync
Recommended Cloud Hosting
Looking for reliable cloud infrastructure? Check out these developer-friendly services.
- Cherry Servers - High-performance VPS and dedicated servers
- Cloudways - Managed cloud hosting for developers