Looping through files in directories, each matching a pattern

6,456
for file in [A-J]*/*.pdf ; do
    : # do something with "$file" here
done
Share:
6,456

Related videos on Youtube

Erwann
Author by

Erwann

x64/LM 19

Updated on September 18, 2022

Comments

  • Erwann
    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
      roaima over 8 years
      Great. What have you tried so far?
  • Erwann
    Erwann over 8 years
    I 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
    Erwann over 8 years
    I may have to do with the whitespaces in the directory, as the proposed solution works with a test case not involving whitespaces.
  • Erwann
    Erwann over 8 years
    @don_crissti, no I don't see what was unclear about my initial question.
  • Erwann
    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
    Alessio over 8 years
    In fact, I quoted "$file" in the comment. That was quite deliberate. I meant do something with "$file" here, not do 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
    Alessio about 5 years
    that'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.