
私のフォルダには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]))
括弧内の文字はglob 修飾子:/
ディレクトリのみを一致させ、om
一致を古い順に並べ替え、[1]
最初の (つまり最新の) 一致のみを保持します。N
のサブディレクトリがない場合に空の配列 (通常は 1 要素の配列) を取得する場合は を追加しますparent
。
あるいは、parent
シェルのグロブ文字が含まれていないと仮定します。
latest_directory='parent/*(/om[1])'; latest_directory=$~latest_directory
zsh を持っていないが、最近の GNU ツール (つまり、非組み込み Linux または Cygwin) を持っている場合は、 を使用できますfind
が、面倒です。1 つの方法は次のとおりです。
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
- date はディレクトリを順序付けし、最後に変更された名前全体を出力します (カットされたデフォルトの区切り文字タブとしていくらかのスペースが含まれている場合でも)