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

fzk*_*zkl 34 arrays bash ls find capture

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

Sie*_*geX 50

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

arr=( $(find /path/to/toplevel/dir -type f) )
Run Code Online (Sandbox Code Playgroud)

$ 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
Run Code Online (Sandbox Code Playgroud)

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

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

  • @ChandanChoudhury`read -r -d $'\ 0'`告诉`read`命令不将反斜杠视为一个特殊的转义字符并用NUL字符分隔每个单词,因为我们告诉`find`将它用作分隔符用`-print0`.`IFS =`部分基本上取消了特殊的内部字段分隔符环境变量,因此它不会在制表符或空格或新行上执行分词.TLDR版本是这些命令使得您可以迭代任何文件名,而不是它包含什么类型的字符. (2认同)

sim*_*mon 9

for i in `ls`; do echo $i; done;
Run Code Online (Sandbox Code Playgroud)

不能比那更简单!

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

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

  • [不解析ls!](http://mywiki.wooledge.org/ParsingLs)`for in in*; do ...`做同样的事情,除了它没有被文件名中的有趣字符混淆,并且运行得更快(因为它不会产生另一个进程). (6认同)
  • `for in in*`更简单! (3认同)
  • @DennisWilliamson有没有办法在$ path/*中使用变量(包含路径)而不是`*`:` (2认同)