2017-04-17 63 views
0

在脚本所在的位置,我有多个子目录,我想在其中对所有内容运行单个命令。内容也按升序编号。在具有10个以上项目的文件夹中使用for f in *会导致在1..9之前顺序出现名为1011的文件。按数字顺序处理文件

此外,每个子目录中的文件数量在6到12个项目之间不等,所以我不认为我可以简单地执行像{1..12}这样的范围操作,因为我想避免关于不存在的文件的警告/错误。

问题:有没有办法强制或修改for循环遍历文件夹中的所有内容不知道的文件夹内容的数量时保持递增顺序?

term=""     # hold accumulated filenames 

for d in */ ; do   # iterate over sub-directories 
    cd $d 
    for f in * ; do  # iterate over files in sub-directory 
     term="$term $f" 
    done 
    # run a command using the string $term 
    term="" 
    cd .. 
done 

边注:我标记shshellbash因为他们都适用于这个问题。在添加两个标记之前,我阅读Difference between sh and bash,以确保它是一个有效的选择,即使存在一些语法/可移植性的变化等。

回答

1

为此,您可以使用ls选件-v。从man ls

-v natural sort of (version) numbers within text

如果从ls改变你的内循环,以

for f in `ls -v` ; do  # iterate over files in sub-directory 
    term="$term $f" 
done 

结果进行排序数字升序进行排序。

另一种选择是sort,从man sort

-g, --general-numeric-sort compare according to general numerical value

配管从ls结果通过sort -g给出相同的结果。

编辑

因为使用的ls输出来获得文件名is a bad idea,还可以考虑使用替代find,例如

for f in `find * -type f | sort -g`; do 
    ... 
+0

感谢@resc示例,它有帮助。 –