OSX: Execute same command on all files within a folder

Eyeball picture Eyeball · May 21, 2013 · Viewed 12.6k times · Source

i am using a command-line tool called TMX (https://github.com/tonybeltramelli/TMXResolutionTool) I want to execute this command on every .png file in a certain folder. How can i do that?

This is how it is used:

TMXResolutionTool <tmx path> <resize ratio>
TMXResolutionTool <image path> <resize ratio>
TMXResolutionTool <image path> <new width> <new height>

Cheers.

Answer

dodgethesteamroller picture dodgethesteamroller · May 21, 2013

I think a for/do loop is clearer and probably a little faster than find plus xargs. Assuming you are using the default shell, bash, on OS X, the general form of the command if you want to do it as a one-liner is:

for f in <files>; do <somecommand> $f; done

where <files> is an expression that evaluates to a list of files (usually a wildcard expansion), <somecommand> is the command line that you want executed for each file, and $f expands to each file in <files> in turn. So you'd type something like this:

for f in myfolder/*; do TMXResolutionTool $f <otherparameters> ; done

You can also run multiple commands inside the loop on the same line just by chaining them with semicolons. So, if your question means that you want to run TMXResolutionTool three times on each file in sequence with different parameters:

for f in myfolder/*; do TMXResolutionTool $f <otherparameters>; TMXResolutionTool $f <differentparameters>; TMXResolutionTool $f <yetmoredifferentstuff>; done

By the way, this is all basic bash shell tricks; it's not specific to OS X. Any book on bash will tell you all this and more (although if you want to learn about the command line from a Mac perspective, I recommend the O'Reilly book Learning Unix for OS X Mountain Lion).