How it works...

The xargs command works by accepting input from stdin, parsing the data into individual elements, and invoking a program with these elements as the final command line arguments. By default, xargs will split the input based on whitespace and execute /bin/echo.

Splitting the input into elements based on whitespace becomes an issue when file and folder names have spaces (or even newlines) in them. The My Documents folder would be parsed into two elements My and Documents, neither of which exists.

Most problems have solutions and this is no exception.

We can define the delimiter used to separate arguments. To specify a custom delimiter for input, use the -d option:

$ echo "split1Xsplit2Xsplit3Xsplit4" | xargs -d X
split1 split2 split3 split4

In the preceding code, stdin contains a string consisting of multiple X characters. We define X to be the input delimiter with the -d option.

Using -n along with the previous command, we can split the input into multiple lines of two words each as follows:

$ echo "splitXsplitXsplitXsplit" | xargs -d X -n 2
split split
split split

The xargs command integrates well with the find command. The output from find can be piped to xargs to perform more complex actions than the -exec option can handle. If the filesystem has files with spaces in the name, the find command's -print0 option will use a 0 (NULL) to delimit the elements, which works with the xargs -0 option to parse these. The following example searches for .docx files on a Samba mounted filesystem, where names with capital letters and spaces are common. It uses grep to report files with images:

$ find /smbMount -iname '*.docx' -print0 | xargs -0 grep -L image