Linux: find xargs

By Xah Lee. Date: .

xargs

xargs is a command that is used together with find to allow you to call arbitrary unix commands on list of files.

there are many version of xargs, their options are incompatible.

on this page, we talk about gnu xargs.

use “find” on file names that may contain spaces or dash

# print file names that may contain spaces
find . -print0 | xargs -0 -l -i echo "{}";
-print0
use null char (ASCII 0) as file name separator. (by default -print uses newline character.)

Here's the options used for xargs:

-0
parse input using null char as seperators and take any special char in file name as literal.
-l
pass just one file name at a time.
-i
use {} as placeholder for file name.
"{}"
Quote around the entire file name, so that echo (or another program) will see it as one argument instead of several. (Note: the -i must come after -l)

Here's a useful example:

# convert all png in a dir to jpg
# file name should not contain ttt. if so, change ttt to hhh or something random

find . -name "*png" -print0 | xargs -0 -L1 -I ttt magick ttt ttt.jpg

Use GNU Parallel for xargs

Note: a modern replacement for xargs is GNU parallel. The syntax is almost indentical to xargs, except it runs in parallel. It also doesn't have problems with file names containing quotes or apostrophes.

Thanks to author of GNU Parallel, Ole Tange for telling me about it.

Linux, Files and Dirs