
我的資料夾parent
包含以下內容:
A.Folder B.Folder C.File
它裡面有資料夾和文件。B.Folder
較新。現在我只想得到B.Folder
,我怎麼才能實現這個目標?我試過這個,
ls -ltr ./parent | grep '^d' | tail -1
但它給了我drwxrwxr-x 2 user user 4096 Jun 13 10:53 B.Folder
,但我只需要名字B.Folder
。
答案1
嘗試這個:
$ ls -td -- */ | head -n 1
-t
選項ls
按修改時間排序,最新的在前。
如果你想刪除/
:
$ ls -td -- */ | head -n 1 | cut -d'/' -f1
答案2
答案3
zsh 強制回答:
latest_directory=(parent/*(/om[1]))
括號中的字元是全域限定符:/
僅匹配目錄,om
按年齡增長對匹配項進行排序,並[1]
僅保留第一個(即最新的)匹配項。如果N
沒有.parent
或者,假設parent
不包含任何 shell 通配符:
latest_directory='parent/*(/om[1])'; latest_directory=$~latest_directory
如果你沒有 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")
有一個簡單的解決方案ls
,只要目錄名稱不包含換行符或(在某些系統上)不可列印字符,該解決方案就可以工作:
latest_directory=$(ls -td parent/*/ | head -n1)
latest_directory=${latest_directory%/}
答案4
即使目錄名稱包含空格,以下指令也能完成這項工作:
cp `find . -mindepth 1 -maxdepth 1 -type d -exec stat --printf="%Y\t%n\n" {} \; |sort -n -r |head -1 |cut -f2'`/* /target-directory/.
反引號中內容的更新解釋是:
.
- 目前目錄(您可能想在此處指定絕對路徑)-mindepth/-maxdepth
- 將 find 指令限制在目前目錄的直接子目錄-type d
- 僅目錄-exec stat ..
- 輸出修改時間和目錄名稱,用製表符(而不是空格)分隔sort -n -r |head -1 | cut -f2
- 日期對目錄進行排序並輸出最近修改的完整名稱(即使包含一些空格作為剪切預設分隔符號標籤)