Looping through files in directories, each matching a pattern
6,456
for file in [A-J]*/*.pdf ; do
: # do something with "$file" here
done
Related videos on Youtube
Comments
-
Erwann over 1 year
I want to loop over files matching
*.pdf
, in the directories matching[A-J]*
?I don't understand what is unclear about this question that resulted in putting it on hold.
-
roaima over 8 yearsGreat. What have you tried so far?
-
-
Erwann over 8 yearsI see the intuition behind this, but it doesn't work in my case. If, say, "do something" is
echo $file
, it prints[A-J]*/*.pdf
-
Erwann over 8 yearsI may have to do with the whitespaces in the directory, as the proposed solution works with a test case not involving whitespaces.
-
Erwann over 8 years@don_crissti, no I don't see what was unclear about my initial question.
-
Erwann over 8 years@don_crissti, how could an answer be "perfectly fine" if the question is ill posed, as you claim? (rhetorical) And yes, cas' answer is spot on, and that ends the matter for me. Thanks.
-
Alessio over 8 yearsIn fact, I quoted "$file" in the comment. That was quite deliberate. I meant
do something with "$file" here
, notdo something with $file here
. And, no, it won't print the literal string[A-J]*/*.pdf
unless that glob doesn't match any files...which contradicts your original question. -
Alessio about 5 yearsthat's what will happen if there are NO directories matching the pattern (i.e. beginning with a letter from A-J) containing files ending in
.pdf
- because if a shell glob pattern doesn't match anything, the shell will treat it as a literal string. If any such directories/files exist, the loop will iterate through the matching .pdf file(s). The "do something" above should include a test to check whether$file
exists before any action.