Bash脚本:创建一个目录下所有文件的数组

35

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

import os
fileList = os.listdir("myDir")
myFileNames=$(ls ~/myDir)

for file in $myFileNames; 
#do something

但是我希望能够拥有一个计数器变量,并且像以下代码一样使用逻辑:

 while $counter>=0;
   #do something to myFileNames[counter]
我对shell脚本很陌生,无法弄清楚如何实现,因此希望得到有关此问题的任何帮助。
3个回答

61

您可以做:

# 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

1
如果你想限制for循环的运行次数,你可以进行以下修改:counter=10 for ((i=0; i<${#arr[@]} && i - andypea
6
实际上,在创建数组之前使用 shopt -s nullglob 可以避免得到任何错误结果。 - anubhava
1
在顶部使用 arr=(~/myDir/*.txt) 来匹配扩展名为 txt 的文件。 - anubhava
1
那么最好先执行 cd myDir,然后再执行 arr=(*.txt) - anubhava
2
@HenkPoley:好主意。我已经添加了shopt -s nullglob来解决这个问题。 - anubhava
显示剩余5条评论

8

您的解决方案可以用于生成数组。但不要使用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不包含空格,那么你就没问题了。 - Paul Hicks
OP没有提到这是标准的一部分 :) - Paul Hicks

1
# 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接