30 Jun 2011

The wonder of xargs

If you’re ever sat at the linux commandline and had a repetitive task to complete on some files or directories then you’ll find “xargs” together with “find” a very useful combination.

Find will return a list of files and directories, one per line which can be piped into xargs so that the same command can be repeated on each file found, for instance:

find *.png

Will find .png files in the current directory. If you wanted to change the permissions on just these .png files you could then pipe the output into xargs:

find *.png | xargs chmod 775 -v

The other day I wanted to change the permissions for a subfolder called “logs” that was in 10+ folders:

find . -maxdepth 2 -name "logs" | xargs chmod 755 -v

Naturally, one should test the find to see what is returned before piping the result into an xargs, especially if you’re doing something that cannot be easily undone (like rm for instance).

The final thing that is worth knowing about is argument replacement. All the above examples assume that it is ok to put the result of the find command on the end of the xargs command, but if you were doing a rename operation or a copy this wouldn’t be the case. In the case below I’ve used the -I xargs command to define an identifier which will be swapped for the result from find:

find . -maxdepth 2 -name "logs" | xargs -I xxx mv xxx xxx.l

So if one of the lines coming from find is “subfolder/logs” then the mv command executed will be:

mv subfolder/logs subfolder/logs.l
comments powered by Disqus