首页 > 解决方案 > 获取 bash 中 find 命令返回的数组的最后一项

问题描述

我有命令:

bigfiles=$(find "${path}/" -printf '%s %p\n'| sort -nr | head -2 | sed 's/^[^ ]* //')

现在我想得到最后一个项目

anotherfile=$bigfiles[1]

它似乎是空的

如何从find命令中获取结果的第 n 个元素?

标签: bash

解决方案


通过使用mapfilewhich is a bash4+ feature,可能会做你想做的事。

mapfile -t bigfiles < <(find "${path}/" -printf '%s %p\n'| sort -nr | head -2 | sed 's/^[^ ]* //')

anotherfile=${bigfiles[-1]}
echo "$anotherfile"
  • -1是数组中的最后一个元素/项。

  • 如果您只对 find 的 output 的最后一项感兴趣,您可以将输出通过管道传输到tail或者head取决于您尝试使用它执行的操作。


推荐阅读