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
A useful tool.

August 14th, 2011 at 4:05 am
Hi Matt,
First thanks for sharing knowledge and giving your time and expertise.
I would like to add some more tips, looking for efficiency.
1. In Unix file systems, everything is a file, of various types.
When searching for specific file types, adding file type will help to process the right targets.
For instance, when searching for folders,
instead of:
find . -maxdepth 2 -name “logs”
this will target only directory:
find . -maxdepth 2 -type d -name “logs”
Accordingly, when searching for files, search can be:
find *.png -type f
This should be done at least to prevent processing wrong types.
I have no idea whether this increase performance or not, the basic measurement I made (with [time] command) did not give me a clear picture.
– Philippe
November 9th, 2011 at 4:47 am
Thanks Phillippe.