0

Background

Converting images from RGB to grayscale. A number of files exist in different directories. For example:

outline/trigon.png
outline/oval-bw.png
outline/crescent-bw.png
outline/trigon-bw.png
outline/crescent.png
outline/oval.png

Problem

Iterate over a set of files (without a hyphen) and convert them to grayscale, without including files that have already been converted. Files that have already been converted have file names ending with -bw.png. The script should avoid creating -bw-bw.png files.

Solution

The following line will iterate over only the files that have not been converted:

for i in $(find ./stripe/ ./outline ./solid -name "*.png" -exec echo {} \; | grep -v "-"); do

The full script:

#!/bin/bash

# Avoid converting existing B&W files...
for i in $(find ./stripe/ ./outline ./solid -name "*.png" -exec echo {} \; | grep -v "-"); do
  SHAPEDIR=$(dirname $i)
  SHAPENAME=$(basename $i .png)
  OUTPUTSHAPE=$SHAPEDIR/$SHAPENAME-bw.png
  echo "convert $i to $OUTPUTSHAPE ..."
  convert $i -density 600 -colorspace gray $OUTPUTSHAPE
done

Question

What's a simpler way to iterate over all files while ignoring any file that has a hyphen (e.g., -bw) in its name? (Using find and echo and grep seems obtuse.) This is an academic question, as the solution works.

1

With bash extended globbing patterns:

$ shopt -s extglob
$ echo outline/!(*-*)
outline/crescent.png outline/oval.png outline/trigon.png
  • 1
    Since that pattern alone would match other things apart from png, I suggest this one instead: for i in @(stripe|outline|solid)/@(!(*-bw).png); do. – NuTTyX Sep 23 '14 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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