Command-Line – Run a Command on All Subfolders

command linedirectoryfileswildcards

If you have a series of subfolders (like from a to z) and want to run a command on each one of them (like rm *.pdf or ls *.pdf), how do you do that? The "manual" approach would be cd a, rm *.pdf, or ls *.pdf, cd .., cd b, … That seems too complicated, so I believe there must be an easier approach.

Best Answer

Try doing this (using , brace expansion & globs):

rm -f {a..z}/*.pdf

or

rm -f [a-z]/*.pdf

if your shell lack the brace expansion feature.

Contrary to [a-z], {a..z} (also supported by ksh93) is not a glob, it's brace expansion, it's expanded (before globs) regardless of whether files exist or not. That's like rm -f a/*.pdf b/*.pdf..., regardless of whether a, b... exist or not. Also note that contrary to [a-z] where the range may be locale dependant (like may include é, ś...), {a..z} only works with byte ranges (and reliably only in the ASCII letter ranges, and number ranges)

(Merci Stephane Chazelas for explanations)