user8510929
user8510929

Reputation:

Calling a program in a loop with matching files

I have a lot of png files within a workdir that can be grouped according to the class defined in the name at the end of each of the file. For example for the case with 3 classes, it should be:

# all files for class1
a1.b1.c1__class1.png
a2.b2.c2__class1.png
..
aN.bN.cN__class1.png


# all files for class2
a1.b1.c1__class2.png
a2.b2.c2__class2.png
..
aN.bN.cN__class2.png

# all files for class3
a1.b1.c1__class3.png
a2.b2.c2__class3.png
..
aN.bN.cN__class3.png

Now I need to write some simple bash script with a loop function that during each time of execution will take all of the files but only for the unique class in order to pass them to some program e.g

for /workdir/*.png; do 
program *__class*.png #  each step only the pngs of the unique class should be recognized!
done

A question: How to apply some filter to specify the application of program each time for the files of unique class?

Upvotes: 2

Views: 30

Answers (2)

codeforester
codeforester

Reputation: 42999

To make your code immune to "argument list too long" error which can happen when there are a large number of files, you could use find ... | xargs ... in a loop like this:

#!/bin/bash

for class_id in {1..3}; do
    find workdir -type f -name "*__class$class_id.png" -print0 | xargs -0 program
done
  • find -print0 produces a null terminated list of matching files
  • xargs -0 processes the null terminated stream of strings read from the pipe

This will make sure that files with whitespace in them are handled properly.

Upvotes: 0

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

From files description what about

for class_id in 1 2 3; do
    program *__class${class_id}.png
done

or using quotes if can contain space or other special character

for class_id in 1 2 3; do
    program *"__class${class_id}.png"
done

Upvotes: 1

Related Questions