The wonders of ’xargs’

xargs has become one of my favourite unix commands. Since I have discovered it, I have continued to use it as often as possible because it can make so many long and difficult tasks quick and easy. Simply put xargs can take a list of input and place each line of the list as an argument to the specified utility. So:

$ <list> | xargs <cmd> <Line #1 of list> 

This would then continue to iterate through the complete list. If for example the text file foo.txt contained a list of file names you can complete the following examples where we are copying a list of files to /foo/bar/
$ cat foo.txt | xargs cp /foo/bar/

or
$ls *.sh | xargs cp /foo/bar/

by default xargs uses the delimiter’s of space, tab, newline and end-of-file to seperate the list of arguements but if for example you are using find you must do the following:
$find /foo/bar -print0 | xargs -0 cp /another/example/

the -0 changes xargs to expect NUL (``\0’‘) characters as separators. This is because find, when printing to standard output, is not using one of the above mentioned delimiters.

At the moment we are only appending our list as the last arguement of our command. I now introduce the -J paramater. A snippet from the man page:

If this option is specified, xargs will use the data read from standard input to replace the first occurrence of replstr instead of appending that
             data after all other arguments. 

So for example

$find /foo/bar -mtime +1w | xargs -J % scp % user@example.com:~

this would find any file in /foo/bar older than a week and scp it to my example.com machine in the home directory of the user.

Latest News

Syndicate content