如何按数字顺序和修改时间顺序对文件名进行排序?

Léo*_* 준영 4 zsh pdf sort files

我想通过pdfjoin/ pdfunite/... 以在线程回答linux 命令合并 pdf 文件与数字排序修改时间顺序中讨论的数字顺序加入 pdf 文件。如果您在线程中使用解决方案,它会按数字顺序和字母顺序排列顺序。这是与文件名,例如,你看到两个一分精度具有相同的修改时间问题,但Visceral早以第二精度(文件浏览器注意事项,并放Visceral第一位Modified的顺序。

Filename               Modified
-----                  ---
3.THE ABC.pdf          10:39 
3.Visceral abc..pdf    10:39
Run Code Online (Sandbox Code Playgroud)

完整的文件名

1.Description abc.pdf
2.Gabcd.pdf
3.THE ABC.pdf
3.Visceral abc..pdf
4.description of abc.pdf
5.Chraa..pdf
Run Code Online (Sandbox Code Playgroud)

提案 #1 按数字和字母顺序起作用,但不按数字和修改顺序起作用

# /sf/answers/1655048111/
ls -v *.pdf | ...
    bash -c 'IFS=$'"'"'\n'"'"' read -d "" -ra x;pdfunite "${x[@]}" output.pdf'
Run Code Online (Sandbox Code Playgroud)

提案 #2 简化案例,但不处理文件名中的空格和其他特殊字符

# /sf/answers/1655048111/
pdfunite $(ls *.pdf | sort -n) output.pdf
Run Code Online (Sandbox Code Playgroud)

pdfunite --help关于排序没有任何内容,所以我认为它应该由ls/ sort/... 完成该命令在其手册页sort中没有任何内容modified

测试 xhienne 的答案

您看到的输出中的顺序不正确,2.jpg并且4.jpg由于某种原因顺序错误

masi@masi:~/Documents$ ls -tr /home/masi/Documents/[0-9]* | sort -t. -k1,1n -s
/home/masi/Documents/1.jpg
/home/masi/Documents/3.jpg
/home/masi/Documents/5.jpg
/home/masi/Documents/6.jpg
/home/masi/Documents/7.jpg
/home/masi/Documents/8.jpg
/home/masi/Documents/9.jpg
/home/masi/Documents/10.jpg
/home/masi/Documents/2.jpg
/home/masi/Documents/4.jpg
Run Code Online (Sandbox Code Playgroud)

第二次迭代

export LC_ALL=C; ls -tr /home/masi/Documents/[0-9]* | sort -t. -k1,1n -s
Run Code Online (Sandbox Code Playgroud)

输出

/home/masi/Documents/1.jpg
/home/masi/Documents/3.jpg
/home/masi/Documents/5.jpg
/home/masi/Documents/6.jpg
/home/masi/Documents/7.jpg
/home/masi/Documents/8.jpg
/home/masi/Documents/9.jpg
/home/masi/Documents/10.jpg
/home/masi/Documents/2.jpg
/home/masi/Documents/4.jpg
Run Code Online (Sandbox Code Playgroud)

操作系统:Debian 8.5

don*_*sti 5

你可以这样做zsh

zmodload zsh/stat

prefixmtime () {
sortstring=${(l:6::0:)${REPLY%%.*}}$(zstat -F '%s' +mtime -- $REPLY)
REPLY=${sortstring}
}

print -rl -- *(o+prefixmtime)
Run Code Online (Sandbox Code Playgroud)

print -rl如果您对结果满意,请替换为您的命令


工作原理:
globs 将o+function根据函数prefixmtime返回的内容在此处(通过)排序,即sortstring通过连接每个文件名的数字前缀获得的字符串,${REPLY%%.*}填充为零(l:6::0:)(假设前缀最多 6 个字符长)所述mtime以秒(通过获得zstat模块)。如果您运行,可能更容易理解它是如何工作的:

{ for f (*)
printf '%s %s\n' ${(l:6::0:)${f%%.*}}$(zstat -F '%s' +mtime -- $f) $f
} | sort -k1,1n
Run Code Online (Sandbox Code Playgroud)

请注意,以上假设您与文件位于同一目录中,否则您必须将该函数中的排序字符串定义为

sortstring=${(l:6::0:)${${REPLY##*/}%%.*}}$(zstat -F '%s' +mtime -- $REPLY)
Run Code Online (Sandbox Code Playgroud)

然后你可以使用目录路径,例如

print -rl some/place/else/*(o+prefixmtime)
Run Code Online (Sandbox Code Playgroud)