如何获取当前目录下所有文件的列表及其修改日期并按该日期排序?
现在我知道如何使用find,stat和来实现这一点sort,但是由于某种奇怪的原因,stat它没有安装在盒子上,我不太可能安装它。
还有其他选择吗?
PS:gcc也没有安装
Gil*_*il' 27
我最短的方法使用 zsh:
print -rl -- **/*(.Om)
Run Code Online (Sandbox Code Playgroud)
(D如果您还想列出隐藏文件或隐藏目录中的文件,请添加glob 限定符)。
如果你有 GNU find,让它打印文件修改时间并以此排序。我假设文件名中没有换行符。
find . -type f -printf '%T@ %p\n' | sort -k 1 -n | sed 's/^[^ ]* //'
Run Code Online (Sandbox Code Playgroud)
如果您有 Perl(再次假设文件名中没有换行符):
find . -type f -print |
perl -l -ne '
$_{$_} = -M; # store file age (mtime - now)
END {
$,="\n";
print sort {$_{$b} <=> $_{$a}} keys %_; # print by decreasing age
}'
Run Code Online (Sandbox Code Playgroud)
如果您有 Python(再次假设文件名中没有换行符):
find . -type f -print |
python -c 'import os, sys; times = {}
for f in sys.stdin.readlines(): f = f[0:-1]; times[f] = os.stat(f).st_mtime
for f in sorted(times.iterkeys(), key=lambda f:times[f]): print f'
Run Code Online (Sandbox Code Playgroud)
如果您可以通过 SSH 访问该服务器,请将目录挂载到设备更好的机器上的sshfs上:
mkdir mnt
sshfs server:/path/to/directory mnt
zsh -c 'cd mnt && print -rl **/*(.Om)'
fusermount -u mnt
Run Code Online (Sandbox Code Playgroud)
仅使用 POSIX 工具要复杂得多,因为没有找到文件修改时间的好方法。检索文件时间的唯一标准方法是ls,并且输出格式依赖于语言环境并且难以解析。
如果您可以写入文件,并且您只关心常规文件,并且文件名中没有换行符,那么这里有一个可怕的混搭:为单个目录中的所有文件创建硬链接,并按修改时间对它们进行排序。
set -ef # disable globbing
IFS='
' # split $(foo) only at newlines
set -- $(find . -type f) # set positional arguments to the file names
mkdir links.tmp
cd links.tmp
i=0 list=
for f; do # hard link the files to links.tmp/0, links.tmp/1, …
ln "../$f" $i
i=$(($i+1))
done
set +f
for f in $(ls -t [0-9]*); do # for each file, in reverse mtime order:
eval 'list="${'$i'} # prepend the file name to $list
$list"'
done
printf %s "$list" # print the output
rm -f [0-9]* # clean up
cd ..
rmdir links.tmp
Run Code Online (Sandbox Code Playgroud)
gee*_*aur 14
假设 GNU find:
find . -printf '%T@ %c %p\n' | sort -k 1n,1 -k 7 | cut -d' ' -f2-
Run Code Online (Sandbox Code Playgroud)
如果您希望首先列出最新的文件,请更改1n,1为1nr,1。
如果您没有 GNU,find它会变得更加困难,因为ls的时间戳格式变化很大(例如,最近修改的文件具有不同的时间戳样式)。
在 Mac 上,没有 -printf 参数可供查找,但您可以这样做:
find . -print0 | xargs -0 -n 100 stat -f"%m %Sm %N" | sort -n|awk '{$1="";print}'