How to recursivly use JpegTran (command line) to o

2020-07-06 04:33发布

问题:

i have Photos in multiple directories. I want to use jpegtran (command line tool) to recursivly go through each one, optimise it, and save it (overwrite it)

if they are all in one folder i use this

for JPEG in *.jpg ; do jpegtran -optimize $JPEG > $JPEG; done

but i can't get it working recursivly and overwriting the same file (rather than to a new filename)

any tips?

回答1:

jpegtran whole directory

find /the/image/path -name "*.jpg" -type f -exec jpegtran -copy none -optimize -outfile {} {} \;


回答2:

How about using the find command:

find /your/dir -name '*.jpg' -exec echo jpegtran -optimize {} \;

Run the command, if you like the output, remove echo to execute it.



回答3:

It is usually a whole lot easier to use find in such cases, because what you want to do is act on a few filenames. The find utility will give you those names. Assuming you have GNU (or maybe even BSD) tools, the following example will illustrate this common scenario.

For example:

$ find ~/images/wallpapers/TEMP/ -type f -iname '*jpg' \
    -exec sh -c 'jpegtran -outfile {}.out -optimize {}; mv {}.out {} ' \;
  1. find looks for all files ending with jpg in the TEMP folder, recursively.
  2. For every full file path found (denoted by `{}'), find will run the command given to -exec
  3. the -exec option cheats and runs several commands instead of one through sh

Notes

cat file > file is not allowed because simultaneously reading from, and writing to the same file is not a well defined or even supported operation in bash.