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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4678418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:04:48  来源:igfitidea点击:

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

arraysbashfindcapturels

提问by fzkl

Need to process files in current directory one at a time. I am looking for a way to take the output of lsor findand store the resulting value as elements of an array. This way I can manipulate the array elements as needed.

需要一次处理一个当前目录下的文件。我正在寻找一种方法来获取lsor的输出find并将结果值存储为数组的元素。这样我就可以根据需要操作数组元素。

回答by SiegeX

To answer your exact question, use the following:

要回答您的确切问题,请使用以下内容:

arr=( $(find /path/to/toplevel/dir -type f) )

Example

例子

$ 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

However, if you just want to process files one at a time, you can either use find's -execoption if the script is somewhat simple, or you can do a loop over what find returns like so:

但是,如果您只想一次处理一个文件,如果脚本有点简单,您可以使用find's-exec选项,或者您可以对 find 返回的内容进行循环,如下所示:

while IFS= read -r -d $'
for i in `ls`; do echo $i; done;
' file; do # stuff with "$file" here done < <(find /path/to/toplevel/dir -type f -print0)

回答by simon

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

can't get simpler than that!

没有比这更简单的了!

edit: hmm - as per Dennis Williamson's comment, it seems you can!

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

edit 2: although the OP specifically asks how to parse the output of ls, I just wanted to point out that, as the commentators below have said, the correct answer is "you don't". Use for i in *or similar instead.

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

回答by marco

You actually don't need to use ls/find for files in current directory.

您实际上不需要对当前目录中的文件使用 ls/find 。

Just use a for loop:

只需使用 for 循环:

shopt -s dotglob

And if you want to process hidden files too, you can set the relative option:

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

ls directory | xargs cp -v dir2

This last command works in bash only.

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

回答by TyrantWave

Depending on what you want to do, you could use xargs:

根据您要执行的操作,您可以使用 xargs:

##代码##

For example. xargs will act on each item returned.

例如。xargs 将作用于返回的每个项目。