【发布时间】:2014-10-07 21:26:24
【问题描述】:
我希望能够获得与特定模式匹配的第一个目录的名称,例如:
~/dir-a/dir-b/dir-*
也就是说,如果目录dir-b 包含目录dir-1、dir-2 和dir-3,我会得到dir-1(或者,dir-3)。
如果dir-b 中只有一个子目录,则上面列出的选项有效,但如果有更多子目录,则显然失败。
【问题讨论】:
我希望能够获得与特定模式匹配的第一个目录的名称,例如:
~/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 命令并将结果打印为“modification_time 文件名”sort 按时间对结果进行排序head 获得第一个cut 削减了无用的时间场您可以使用-mindepth 1 -maxdepth 1 调整查找,以免下降更深。
在 linux 中,它可以更短,(使用 -printf 格式),但这也适用于 OS X...
【讨论】:
echo "${content[@]:(-1)}" 更简单。