我如何捕获从LS输出或find命令存储阵列中的所有文件名? [英] How do I capture the output from the ls or find command to store all file names in an array?

查看:237
本文介绍了我如何捕获从LS输出或find命令存储阵列中的所有文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要在当前目录中的一个在一个时间处理文件。我正在寻找一种方式,采取 LS的输出找到并存储所得到的值作为一个数组的元素。这种方式需要,我可以操纵数组元素。

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

不过,如果你只是想处理文件一次,您可以使用找到的 -exec 选项:

while IFS= read -r -d $'\0' file; do
  # stuff with "$file" here
done < <(find /path/to/toplevel/dir -type f -print0)

这篇关于我如何捕获从LS输出或find命令存储阵列中的所有文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆