37

I have a lot of images that I would like to process with pngquant. They are organized in a pretty deep directory structure, so it is very time-consuming to manually cd into every directory and run pngquant -ext .png -force 256 *.png

Is there a way to get this command to run on every *.png in every directory within the current one, as many layers deep as necessary?

1
  • 2
    What operating system are you on?
    – Manish
    Commented Mar 10, 2012 at 19:30

2 Answers 2

77

If you have limited depth of directories and not too many files, then lazy solution:

pngquant *.png */*.png */*/*.png

A standard solution:

find . -name '*.png' -exec pngquant --ext .png --force 256 {} \;

and multi-core version:

find . -name '*.png' -print0 | xargs -0 -P8 -L1 pngquant --ext .png --force 256

where -P8 defines number of CPUs, and -L1 defines a number of images to process in one pngquant call (I use -L4 for folders with a lot of small images to save on process start).

10
  • 2
    find . -name '*.png' -exec pngquant -ext .png -force 256 {} \; works beautifully for me. Thank you.
    – cmal
    Commented Mar 10, 2012 at 20:05
  • Thank you for the answer, worked like a charm for me. However, could you explain the syntax regarding the number of cores? Is that a pngquant option or a OS option which divides the tasks and gives some images to each thread?
    – Nicolas
    Commented Dec 10, 2012 at 20:23
  • @Stewie that's xargs' option that tells it to run number of tasks in parallel.
    – Kornel
    Commented Dec 11, 2012 at 18:16
  • 3
    Alternatively, depending on whether you have a reasonably recent bash or zsh, and the option is enabled (shopt -s globstar in bash), you can use a recursive glob: pngquant **/*.png
    – gid
    Commented Jun 19, 2013 at 13:40
  • 4
    find . -name '*.png' -exec pngquant --ext .png --force 256 {} \; fails with File not found - '*.png'
    – Sprintstar
    Commented Jan 6, 2014 at 10:15
23

With the fish shell you can run the following from the root of your project directory

pngquant **.png

Which will generate new files with extensions like -or8.png or -fs8.png.

If you want to overwrite the existing files, you can use

pngquant **.png --ext .png --force
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.