...
Is a very useful program to take a list and run commands against that list. xargs will take a list of arguments, loop through them and run a command against 1 or more arguments at a time.
Basic Example
Here is a really straightforward example of using xargs to calculate a MD5 hash on every file in the current directory,
Code Block | ||
---|---|---|
| ||
ls | xargs -t -n1 md5 |
This is how it works,
- -t will show you what xargs is about to execute before it executes it.
- -n1 limits the specifies that xarg work with he arguments passed by the directory to pass one argumentx arguments at a time, in this case one file name argument at a time.
...
Thanks to the -t the output will be shown on screen,
Code Block |
---|
md5 planetary.doc
MD5 (bash) = ab5970d50d67bcafe5c554387f76534e
md5 Superman.jpg
MD5 (cat) = cdefa50d737dfcf8dc57886ea1a758c4
|
Substitution to Rename Files
Now let's get more advanced and use -I to allow substitution. First we'll create a some temporary files,
Code Block | ||
---|---|---|
| ||
mkdir temp
cd temp
touch files1 file2 file3 # Creates 3 empty files |
Now using xargs we will add the txt extension to each file,
Code Block |
---|
ls | xargs -t -I {} mv {} {}.txt
mv file1 file1.txt
mv file2 file2.txt
mv file3 file3.txt |
The -I {} specifies that the arguments by ls will be placed in the location of the {} called the replacement string. In fact you use whatever variable name you want instead of {}. For example, the following will also work,
Code Block | ||
---|---|---|
| ||
ls | xargs -t -n1I varX md5 varX md5 planetaryfile1.doctxt MD5 (bashfile1.txt) = ab5970d50d67bcafe5c554387f76534ed41d8cd98f00b204e9800998ecf8427e md5 Supermanfile2.jpgtxt MD5 (catfile2.txt) = cdefa50d737dfcf8dc57886ea1a758c4 Tin-Phams-iMac:bin tinpham$ |
...
d41d8cd98f00b204e9800998ecf8427e
md5 file3.txt
MD5 (file3.txt) = d41d8cd98f00b204e9800998ecf8427e |
Also, one item I don't understand yet is that it seems to default to 1 argument at a time.
Debugging Xargs with echo
The echo command is useful to test and see what xargs will be looping through,
Code Block | ||
---|---|---|
| ||
ls | xargs -t -I {} echo "mv {} {}.txt" |
Search Inside of Files
Try to memorize this command,
...