Benoit B.
Benoit B.

Reputation: 12044

Bash Looping through directories and filenames

I need to loop through various directories and filenames having the same name, but incrementing by 1, from 001, 002, 003 to 100.

/Very/long/path/to/folder001/very_long_filename001.foobar
/Very/long/path/to/folder002/very_long_filename002.foobar
/Very/long/path/to/folder003/very_long_filename003.foobar


$FILES=/Very/long/path/to/folder*/very_long_filename*.foobar
for f in $FILES
do
  echo "$f"
done

The for loop I wrote above doesn't work, and I really don't understand why ! Any hint ?Thanks.

Upvotes: 0

Views: 2552

Answers (2)

chepner
chepner

Reputation: 530940

First, don't use a dollar sign to assign to a variable:

FILES=/Very/long/path/to/folder*/very_long_filename*.foobar

You don't need a variable at all; you can iterate directly over a glob pattern:

for f in /Very/long/path/to/folder*/very_long_filename*.foobar; do

Upvotes: 2

konsolebox
konsolebox

Reputation: 75458

Use an array instead:

FILES=(/Very/long/path/to/folder*/very_long_filename*.foobar)
for f in "${FILES[@]}"
do
  echo "$f"
done

Another way to make it run in order:

for i in $(seq -w 001 100); do
    f="/Very/long/path/to/folder${i}/very_long_filename${i}.foobar"
    [[ -e $f ]] || continue  ## optional test.
    echo "$f"
done

By the way your for loop doesn't work since you started your assignment with $:

`$FILES=...`

It should simply have been

FILES=/Very/long/path/to/folder*/very_long_filename*.foobar

Still using an array is safer since it preserves spaces within filenames during expansion for for.

Upvotes: 5

Related Questions