按修改时间排序文件

evi*_*oup 8 ls find sort wildcards timestamps

我在这里看到了很多问题和答案,使用的是

list_dir=`ls -t /path/to/dir/`
for i in $list_dir; do
Run Code Online (Sandbox Code Playgroud)

或者

ls -t | while read i; do
Run Code Online (Sandbox Code Playgroud)

现在,我知道您不应该在脚本中使用 ls,因为它很容易中断;但我找不到更好的方法来操作文件,从最后修改到最近修改(反之亦然)。

我可以使用类似的东西:

find . -type f -printf '%T@ %p\n' | sort -n | cut -d ' ' -f 2- | while read i; do...
Run Code Online (Sandbox Code Playgroud)

...但这仍然会破坏名称中包含换行符的任何文件,并且启动起来要丑得多。有没有更好的办法?

Hau*_*ing 8

“不要在脚本中使用 ls”是 POSIX ls“only”的问题;对于 GNU ls,请参见--quoting-style=.

GNU sort 解决了这个问题--zero-terminated

如果它必须兼容,那么您可以find ... -exec一次将一个文件名传递给执行转义的脚本。如果至少有 bash 可用:

start cmd:> testfunc () { echo "${1//$'\n'/\n}"; }
start cmd:> testfunc a$'\n'b
a\nb
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 5

到目前为止,最简单的方法是使用 zsh。的限定符的glob om排序以相反的时间顺序匹配; 使用Om的时间顺序。

for x in /path/to/dir/*(Nom); do …
Run Code Online (Sandbox Code Playgroud)

N如果目录为空,glob 限定符会使模式扩展为空列表。使其*(DNom)匹配点文件。