需要一次一个地处理当前目录中的文件。我正在寻找一种方法来获取 ls
或 find
的输出并将结果值存储为数组的元素。这样我就可以根据需要操作数组元素。
最佳答案
要回答您的确切问题,请使用以下内容:
arr=( $(find /path/to/toplevel/dir -type f) )
例子
$ find . -type f
./test1.txt
./test2.txt
./test3.txt
$ arr=( $(find . -type f) )
$ echo ${#arr[@]}
3
$ echo ${arr[@]}
./test1.txt ./test2.txt ./test3.txt
$ echo ${arr[0]}
./test1.txt
但是,如果您只想一次处理一个文件,您可以使用 find
的 -exec
选项(如果脚本比较简单),或者您可以像这样循环查找返回的内容:
while IFS= read -r -d $'\0' file; do
# stuff with "$file" here
done < <(find /path/to/toplevel/dir -type f -print0)
关于arrays - 如何捕获 ls 或 find 命令的输出以将所有文件名存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4678418/