我希望能够获得与某个模式匹配的第一个目录的名称,例如:
~/dir-a/dir-b/dir-*也就是说,如果目录dir-b包含dir-1、dir-2和dir-3目录,我将得到dir-1 (或者,或者,dir-3)。
如果dir-b中只有一个子目录,那么上面列出的选项就能工作,但如果有更多的子目录,则显然会失败。
发布于 2014-08-14 09:28:29
您可以使用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 .
https://stackoverflow.com/questions/25304466
复制相似问题