让我们假设一个目录包含来自不同相机的图片:
DCIM1234.JPG
DCIM1235.JPG
DCIM1236.JPG
DSCN4120.JPG
DSCN4121.JPG
DSCN4122.JPG
DSCN4123.JPG
IMG5840.JPG
IMG5841.JPG
IMG5842.JPG
IMG5843.JPG
Run Code Online (Sandbox Code Playgroud)
按相机的修改日期对所有这些文件进行排序很容易使用ls -t
。问题是大多数文件系统的精度为 1 秒或以上,因此某些图片可能具有相同的时间戳,例如连拍时。在这种情况下,ls -t
可能会失去文件的自然顺序,这反映在名称中。
如何按修改时间对文件进行排序,同时对修改时间相同的文件按名称排序?
通常,建议避免解析ls
输出。正如上面 didal24 所建议的,stat
是一个更好的选择。
$ stat -c "%Y/%n" *.JPG | sort -t/ -k1,1n -k2 | sed 's@^.*/@@'
Run Code Online (Sandbox Code Playgroud)
从man stat
:
文件的有效格式序列(不带 --file-system):
...
%n 文件名
%Y 上次数据修改的时间,自纪元以来的秒数
因此,stat -c "%Y/%n" *.JPG
将为您提供以秒为单位的时间戳和每个文件的名称,以/
. 例如:
1580845717/IMG5841.JPG
Run Code Online (Sandbox Code Playgroud)
The output of that command is piped to sort -t/ -k1,1n -k2
, which sorts first by the first column, numerically (the timestamp), and then by the second column. Columns are separated by /
(-t/
).
Finally, the output of the sort
command is piped to sed
, which removes all character up to and including the first /
(the chosen delimiter). The result in the list of filenames in the order you wanted (with the "newest" files listed last).
归档时间: |
|
查看次数: |
1366 次 |
最近记录: |