如何捕获 ls 或 find 命令的输出以将所有文件名存储在数组中? [英] How do I capture the output from the ls or find command to store all file names in an array?
本文介绍了如何捕获 ls 或 find 命令的输出以将所有文件名存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要一次处理一个当前目录中的文件.我正在寻找一种方法来获取 ls
或 find
的输出并将结果值存储为数组的元素.这样我可以根据需要操作数组元素.
Need to process files in current directory one at a time. I am looking for a way to take the output of ls
or find
and store the resulting value as elements of an array. This way I can manipulate the array elements as needed.
推荐答案
要回答您的确切问题,请使用以下内容:
To answer your exact question, use the following:
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
选项(如果脚本有点简单),或者您可以对 find 返回的内容进行循环:
However, if you just want to process files one at a time, you can either use find
's -exec
option if the script is somewhat simple, or you can do a loop over what find returns like so:
while IFS= read -r -d $' ' file; do
# stuff with "$file" here
done < <(find /path/to/toplevel/dir -type f -print0)
这篇关于如何捕获 ls 或 find 命令的输出以将所有文件名存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文