【问题标题】:bash script, create array of all files in a directorybash 脚本,在目录中创建所有文件的数组
【发布时间】:2014-03-07 06:26:50
【问题描述】:

我有一个包含许多 .html 文件的目录 myDir。我正在尝试创建目录中所有文件的数组,以便我可以索引该数组并能够引用目录中的特定 html 文件。我尝试了以下行:

myFileNames=$(ls ~/myDir)

for file in $myFileNames; 
#do something

但我希望能够拥有一个计数器变量并具有如下逻辑:

 while $counter>=0;
   #do something to myFileNames[counter]

我对 shell 脚本很陌生,无法弄清楚如何实现这一点,因此希望能提供有关此问题的任何帮助。

【问题讨论】:

    标签: arrays bash shell while-loop


    【解决方案1】:

    你可以这样做:

    # use nullglob in case there are no matching files
    shopt -s nullglob
    
    # create an array with all the filer/dir inside ~/myDir
    arr=(~/myDir/*)
    
    # iterate through array using a counter
    for ((i=0; i<${#arr[@]}; i++)); do
        #do something to each element of array
        echo "${arr[$i]}"
    done
    

    您也可以对数组进行迭代:

    for f in "${arr[@]}"; do
       echo "$f"
    done
    

    【讨论】:

    • 如果你想限制 for 循环的运行次数,你可以做以下修改: counter=10 for ((i=0; i
    • 其实shopt -s nullglob可以在创建数组之前使用,避免得到错误的结果。
    • 要匹配带有txt 扩展名的文件,请在顶部使用arr=(~/myDir/*.txt)
    • 那最好先cd myDirarr=(*.txt)
    • @HenkPoley:好点。我为此添加了shopt -s nullglob
    【解决方案2】:

    您的解决方案将适用于生成数组。不要使用 while 循环,而是使用 for 循环:

    #!/bin/bash
    files=($( ls * )) #Add () to convert output to array
    counter=0
    for i in $files ; do
      echo Next: $i
      let counter=$counter+1
      echo $counter
    done
    

    【讨论】:

    • 在这种情况下使用 IFS 设置字段分隔符。只要 IFS 不包括空间,那么你应该是好的。
    • OP 没有提到这是标准的一部分 :)
    【解决方案3】:
    # create an array with all the filer/dir inside ~/myDir
    arr=(~/myDir/*)
    
    # iterate through array indexes to get 'counter'
    for counter in ${!arr[*]}; do
        echo $counter           # show index
        echo "${arr[counter]}"  # show value
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2023-03-04
      • 2022-11-18
      相关资源
      最近更新 更多