【问题标题】:Bash Looping through directories and filenamesBash 循环遍历目录和文件名
【发布时间】:2013-09-20 18:19:06
【问题描述】:

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

我上面写的for循环不起作用,我真的不明白为什么!任何提示?谢谢。

【问题讨论】:

    标签: bash for-loop directory


    【解决方案1】:

    改用数组:

    FILES=(/Very/long/path/to/folder*/very_long_filename*.foobar)
    for f in "${FILES[@]}"
    do
      echo "$f"
    done
    

    另一种让它按顺序运行的方法:

    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
    

    顺便说一下,自从您使用 $ 开始分配后,您的 for 循环不起作用:

    `$FILES=...`
    

    应该是这样的

    FILES=/Very/long/path/to/folder*/very_long_filename*.foobar
    

    仍然使用数组更安全,因为它会在为 for 扩展期间保留文件名中的空格。

    【讨论】:

    • 感谢您的回复。我来自 Perl,因此 $FILES :-)
    【解决方案2】:

    首先,不要使用美元符号来分配变量:

    FILES=/Very/long/path/to/folder*/very_long_filename*.foobar
    

    你根本不需要变量;您可以直接迭代 glob 模式:

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

    【讨论】:

      猜你喜欢
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多