在 fish shell 中,如何使用通配符和变量遍历文件?

In fish shell, how to iterate over files using wildcard and variable?

如果我运行:

for f in *1000.png
   echo $f
end

我明白了

1000.png
11000.png
21000.png

我想做这样的事情:

for i in 1 2 3
    for f in *$i000.png
         echo $f
    end
end

得到

1000.png
11000.png
21000.png
2000.png
12000.png
22000.png
3000.png
13000.png
23000.png

相反,它什么也不输出。

我也试过:

for i in 1 2
    set name "*"$i"000.png"
    for f in (ls $name)
        echo $f
    end
end

输出:

ls: *1000.png: No such file or directory
ls: *2000.png: No such file or directory

当您尝试在 *$i000.png 中引用 i 变量时,您的 shell 认为 $i000 意味着您正在尝试引用 i000变量,而不是 i 后跟您想要的三个零。

使用 {$var_name} 访问 fish 中的变量,通常 总是 以这种方式引用 shell 变量是个好主意。

所以你的情况,在第二行使用:

    for f in *{$i}000.png

为了避免尝试扩展变量 $i000,您可以

for i in 1 2 3
    for f in *{$i}000.png
         echo $f
    end
end

或者,完全避免外循环:

for f in *{1,2,3}000.png