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

发布于 2024-10-11 15:41:26 字数 81 浏览 0 评论 0原文

需要一次处理当前目录中的一个文件。我正在寻找一种方法来获取 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北城半夏 2024-10-18 15:41:26

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

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 返回的内容进行循环,如下所示:

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

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 -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 
\0' file; do
  # stuff with "$file" here
done < <(find /path/to/toplevel/dir -type f -print0)
听风念你 2024-10-18 15:41:26
for i in `ls`; do echo $i; done;

没有比这更简单的了!

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

编辑2:虽然OP特别询问如何解析ls的输出,但我只是想指出,正如下面的评论者所说,正确的答案是“你不”。使用 for i in * 或类似的方法代替。

for i in `ls`; do echo $i; 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.

江南烟雨〆相思醉 2024-10-18 15:41:26

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

只需使用 for 循环:

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

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

shopt -s dotglob

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

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

Just use a for loop:

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

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

shopt -s dotglob

This last command works in bash only.

潦草背影 2024-10-18 15:41:26

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

ls directory | xargs cp -v dir2

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

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

ls directory | xargs cp -v dir2

For example. xargs will act on each item returned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文