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

问题描述:

如果我运行:在鱼壳中,如何使用通配符和变量遍历文件?

for f in *1000.png 
    echo $f 
end 

我得到

​​

我想这样做:

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}来访问鱼的变量,一般它的一个好主意总是这种方式引用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