gpt4 book ai didi

arrays - bash 脚本,在目录中创建所有文件的数组

转载 作者:行者123 更新时间:2023-11-29 08:45:10 24 4
gpt4 key购买 nike

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

myFileNames=$(ls ~/myDir)

for file in $myFileNames;
#do something

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

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

我是 shell 脚本的新手,无法弄清楚如何实现这一点,因此非常感谢有关此事的任何帮助。

最佳答案

你可以这样做:

# 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

关于arrays - bash 脚本,在目录中创建所有文件的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21668471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com