Command-line construction of auguments list with xargs

by

xargs is a really useful unix command line tool that can be used to construct an argument list for piping into other unix commands.
For example, lets say we want to find and delete all files fitting a certain criteria, such as those with a suffix of “.java~”.
We can use the find utility to easily list these:


$ find . -name *.java~
./path/to/file/file1.java~
./path/to/file/file2.java~
./path/to/file/file3.java~
./path/to/file/file4.java~

However, the output from this is in the form of a list, which cannot be piped directly into a command like rm. If the list is very long, it can be difficult to write it out manually into a singe argument list.

Instead, we can pass the output from the find command into xargs to convert this list into a single argument list for us:


$ find . -name *.java~ | xargs
./path/to/file/file1.java~ ./path/to/file/file2.java~ ./path/to/file/file3.java~ ./path/to/file/file4.java~

This can then be piped into rm or any other command as needed.

This is just one simple example of the use of xargs. It’s a much more powerful tool that is able to handle much larger argument lists with great flexibility.

Advertisements

One Response to “Command-line construction of auguments list with xargs

  1. jens Says:

    Or you could just use “find . -exec <> -name *.java~ ”

    bug ofcourse xargs is verry usefull in some cases 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: