简体   繁体   中英

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM