Bash 选择满足特定模式的单个目录

Bash 选择满足特定模式的单个目录,bash,shell,directory,Bash,Shell,Directory,我希望能够获取与特定模式匹配的第一个目录的名称,例如: ~/dir-a/dir-b/dir-* 也就是说,如果目录dir-b包含目录dir-1、dir-2和dir-3,我将得到dir-1(或者,dir-3) 如果dir-b中只有一个子目录,上面列出的选项就可以工作,但如果有更多子目录,则显然会失败。您可以使用bash数组,如: content=(~/dir-a/dir-b/dir-*) #stores the content of a directory into array "con

我希望能够获取与特定模式匹配的第一个目录的名称,例如:

~/dir-a/dir-b/dir-*
也就是说,如果目录
dir-b
包含目录
dir-1
dir-2
dir-3
,我将得到
dir-1
(或者,
dir-3


如果
dir-b
中只有一个子目录,上面列出的选项就可以工作,但如果有更多子目录,则显然会失败。

您可以使用bash数组,如:

content=(~/dir-a/dir-b/dir-*)     #stores the content of a directory into array "content"
echo "${content[0]}"              #echoes the 1st
echo ${content[${#content[@]}-1]} #echoes the last element of array "comtent"
#or, according to @konsolebox'c comments
echo "${content[@]:(-1)}"
另一种方法是创建一个bash函数,如下所示:

first() { set "$@"; echo "$1"; }

#and call it
first ~/dir-a/dir-b/dir-*
如果要对文件进行排序(不是按名称而是按修改时间),可以使用下一个脚本:

where="~/dir-a/dir-b"
find $where -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f2- -d" "
腐烂的

  • find
    根据定义的条件查找文件
  • xargs
    对找到的每个文件运行stat命令,并将结果打印为“修改时间文件名”
  • sort
    按时间对结果进行排序
  • 获取其中的第一个
  • cut
    将剪切未预期的时间字段
您可以使用
-mindepth 1-maxdepth 1
调整查找,使其不会下降得更深


在linux中,它可以更短(使用-printf格式),但在OSX中也可以…

我喜欢这样,但如何获取最后一个目录?我有根据程序版本命名的目录。我需要获取包含最新版本的目录。
echo“${content[@]:(-1)}”
更容易。@konsolebox已添加,而不是x.)