简体   繁体   English

Bash遍历目录和文件名

[英]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. 我需要遍历具有相同名称的各种目录和文件名,但要从001、002、003到100递增1。

/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 ! 我在上面编写的for循环不起作用,我真的不明白为什么! 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 $ : 顺便说一句for因为您使用$开始分配,所以for循环不起作用:

`$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 . 仍在使用的阵列是更安全的,因为它膨胀用于在保留的文件名内的空间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: 您可以直接在glob模式上进行迭代:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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