【问题标题】:Selecting single directory that satisfies certain pattern选择满足特定模式的单个目录
【发布时间】:2014-10-07 21:26:24
【问题描述】:

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

~/dir-a/dir-b/dir-*

也就是说,如果目录dir-b 包含目录dir-1dir-2dir-3,我会得到dir-1(或者,dir-3)。

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

【问题讨论】:

    标签: bash shell directory


    【解决方案1】:

    您可以使用 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 命令并将结果打印为“modification_time 文件名”
    • sort 按时间对结果进行排序
    • head 获得第一个
    • cut 削减了无用的时间场

    您可以使用-mindepth 1 -maxdepth 1 调整查找,以免下降更深。

    在 linux 中,它可以更短,(使用 -printf 格式),但这也适用于 OS X...

    【讨论】:

    • 我喜欢这个,但是如何获取最后一个目录呢?我有根据程序版本命名的目录。我需要获取包含最新版本的目录。
    • echo "${content[@]:(-1)}" 更简单。
    • @konsolebox 添加,谢谢。 :)
    猜你喜欢
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2011-12-28
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多