繁体   English   中英

如何捕获ls或find命令的输出以将所有文件名存储在数组中?

[英]How do I capture the output from the ls or find command to store all file names in an array?

需要一次处理一个当前目录中的文件。 我正在寻找一种方法来获取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)
for i in `ls`; do echo $i; done;

不能比那更简单!

编辑:嗯 - 根据丹尼斯威廉姆森的评论,似乎你可以!

编辑2:虽然OP专门询问如何解析ls的输出,但我只想指出,正如下面的评论员所说,正确答案是“你没有”。 for i in *或类似的for i in *

实际上,您不需要在当前目录中使用ls / find for files。

只需使用for循环:

for files in *; do 
    if [ -f "$files" ]; then
        # do something
    fi
done

如果您也想处理隐藏文件,可以设置相对选项:

shopt -s dotglob

最后一个命令仅适用于bash。

根据您的想法,您可以使用xargs:

ls directory | xargs cp -v dir2

例如。 xargs将对返回的每个项目执行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM