arrays - 将 find 命令的输出存储在数组中

标签 arrays bash

<分区>

如何将 find $1 的结果放入数组中?

在 for 循环中:

for /f "delims=/" %%G in ('find $1') do %%G | cut -d\/ -f6-

最佳答案

我想哭。

在 bash 中:

 file_list=()
 while IFS= read -d $'\0' -r file ; do
     file_list=("${file_list[@]}" "$file")
 done < <(find "$1" -print0)

 echo "${file_list[@]}"

file_list现在是一个包含 find "$1 结果的数组

“字段 6”有什么特别之处?不清楚你试图用你的 cut 做什么命令。

是否要剪切第6个目录之后的每个文件?

for file in "${file_list[@]}" ; do
    echo "$file" | cut -d/ -f6-
done

但为什么是“字段 6”?我可以假设您实际上只想返回路径的最后一个元素吗?

for file in "${file_list[@]}" ; do
    echo "${file##*/}"
done

甚至

echo "${file_list[@]##*/}"

这将为您提供数组中每个路径的最后一个路径元素。你甚至可以对结果做些什么

for file in "${file_list[@]##*/}" ; do
    echo "$file"
done

bash 程序元素的解释:

(应该改用内置的 readarray)

find "$1" -print0

查找内容并“在标准输出上打印完整的文件名,后跟一个空字符”。这很重要,因为我们稍后会用空字符拆分该输出。

<(find "$1" -print0)

“过程替换”:find 的输出子进程通过 FIFO 读入(即 find 子进程的输出在这里表现得像一个文件)

while ... 
done < <(find "$1" -print0)

find 的输出子进程由 while 读取命令通过 <

IFS= read -d $'\0' -r file

这是 while 条件:

read

读取一行输入(来自 find 命令)。 read 的返回值|除非遇到 EOF,否则为 0,此时 while 退出。

-d $'\0'

...将空字符作为定界符(请参阅 bash 联机帮助页中的引用)。这样做是因为我们使用了空字符 -print0早些。

-r

反斜杠不被视为转义字符,因为它可能是文件名的一部分

file

结果(实际上是第一个词,这里是唯一的)被放入变量file

IFS= 

命令以 IFS 运行,包含 read 上的字符的特殊变量将输入拆分为未设置的单词。因为我们不想 split 。

在循环中:

file_list=("${file_list[@]}" "$file")

在循环内部,file_list 数组增长了 $file。 , 适当引用。

关于arrays - 将 find 命令的输出存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8213328/

相关文章:

php - 如何将MySQLi结果集加载到二维数组中?

Java:将数组列表转换为带有添加元素的数组

arrays - 将整个 2D 压缩数组分配给具有相同元素数量的 1D 压缩数组

linux - 我们可以将 Perl 脚本中使用的变量设置为环境变量吗?

linux - BASH : How to make a script that make “tail -f” always logging the last file in a directory,直播

Java计算方法返回1.0而不是0.5?做什么?

Javascript 数组未获取正确的数据

macos - 在 bash 中, "for;do echo;done"在空格处拆分行

linux - 并行运行脚本命令

php - bash 脚本将在 cron 上运行