Dan*_*iel 21 ls shell timestamps files
我的文件夹parent
有以下内容:
A.Folder B.Folder C.File
Run Code Online (Sandbox Code Playgroud)
它里面有文件夹和文件。B.Folder
较新。现在我只想得到B.Folder
,我怎么能做到这一点?我试过这个,
ls -ltr ./parent | grep '^d' | tail -1
Run Code Online (Sandbox Code Playgroud)
但它给了我drwxrwxr-x 2 user user 4096 Jun 13 10:53 B.Folder
,但我只需要名字B.Folder
。
cuo*_*glm 33
尝试这个:
$ ls -td -- */ | head -n 1
Run Code Online (Sandbox Code Playgroud)
-t
选项ls
按修改时间排序,最新的在前。
如果你想删除/
:
$ ls -td -- */ | head -n 1 | cut -d'/' -f1
Run Code Online (Sandbox Code Playgroud)
ls -td -- ./parent/*/ | head -n1 | cut -d'/' -f2
Run Code Online (Sandbox Code Playgroud)
与Herson 解决方案的不同之处在于 之后的斜杠*
,这使得 shell 忽略所有非 dir 文件。与Gnouc 的区别,如果您在另一个文件夹中,它会起作用。
Cut 需要知道父目录的数量 (2) 才能删除尾随的“/”。如果没有,请使用
VAR=$(ls -dt -- parent/*/ | head -n1); echo "${VAR::-1}"
Run Code Online (Sandbox Code Playgroud)
zsh 强制回答:
latest_directory=(parent/*(/om[1]))
Run Code Online (Sandbox Code Playgroud)
括号中的字符是全局限定符:/
仅匹配目录,om
按年龄增长对匹配项进行排序,并[1]
仅保留第一个(即最新的)匹配项。如果N
没有parent
.
或者,假设parent
不包含任何 shell 通配符:
latest_directory='parent/*(/om[1])'; latest_directory=$~latest_directory
Run Code Online (Sandbox Code Playgroud)
如果你没有 zsh 但有最新的 GNU 工具(即非嵌入式 Linux 或 Cygwin),你可以使用find
,但它很麻烦。这是一种方法:
latest_directory_inode=$(find parent -mindepth 1 -maxdepth 1 -type d -printf '%Ts %i\n' | sort -n | sed -n '1 s/.* //p')
latest_directory=$(find parent -maxdepth 1 -inum "$latest_directory_inode")
Run Code Online (Sandbox Code Playgroud)
有一个简单的解决方案ls
,只要目录名称不包含换行符或(在某些系统上)不可打印字符,该解决方案就可以工作:
latest_directory=$(ls -td parent/*/ | head -n1)
latest_directory=${latest_directory%/}
Run Code Online (Sandbox Code Playgroud)