Search This Blog


Using xargs

Being careful with spaces
Spaces are determined to be new arguments as well as new-lines are determined to be new arguments as well. To prevent this you need to use -0

xargs -0

find . -iname "time*" | xargs 
./not_backedup/timedOut.txt ./time out

find . -iname "time*" | xargs -0
./time out

As you can see it separates each filename with a newline vs xargs being confused and taking in each space as a new argument

Taking multiple arguments as input
echo 1 2 3 4 | xargs -n 2
1 2
3 4

Using redirected stdin from one command in commands that require multiple arguments.

Example: Moving a files that match one criteria to another location
find . -iname "powerOn-00*" -print0 -d 0 | xargs -0 -I {} mv {} configs/ 

The above matches files called powerOn-00* and moves them to the configs directory

We use the -I to define what characters are defined as our standard input xargs received. We later use the defined {} symbol in another command (in this case mv).

Using Arguments Multiple Times
The -c option of sh command causes the commands to be read from the string operand instead of from the standard input. Keep in mind that this option only accepts a single string as its argument, hence multi-word strings must be quoted.

find /usr/home -type f -print0 | xargs -0 -I {} sh -c 'cmd1 "{}" ; cmd2 "{}" ; cmd3 "{}"'

find /usr/home -type f -print0 | xargs -0 -I {} sh -c 'ls -ld "{}" ; file "{}"'
Note: the double quotes are required if the filename contains a space.

Example - Displaying the contents of all files in a directory along with their associated filename
ls | xargs -I % sh -c 'echo % && cat %'


No comments:

Post a Comment