查找名称相似的文件,删除最旧的文件,重命名最新的文件

val*_*epu 5 shell rename files

我有这种情况,在不同的子文件夹中有很多具有相似名称的文件(但它们都遵循一种模式)

file1
file1 (Copy)
/folder1/file2.txt
/folder1/file2 (Copy).txt
/folder1/file3.png
/folder1/file3 (Copy).png
Run Code Online (Sandbox Code Playgroud)

每个文件都在其副本的同一个文件夹中并具有相同的扩展名,不同的是它(Copy)在名称的末尾

我想获取所有这些文件并删除最旧的文件,然后最终将文件重命名为,例如,如果需要重命名file1 (Copy)file1(即删除(Copy)后缀)。

我正在考虑使用findmv但我不知道如何告诉它移动最新的。

Rom*_*est 4

扩展find+bash解决方案(还需要GNU实现stat):

\n\n
find . -type f -name "* (Copy).*" -exec bash -c \'p="${0%/*}"; bn="${0##*/}"; \n        main_bn="${bn/ (Copy)/}"; \n        if [ -f "$p/$main_bn" ]; then \n           t_copy_file=$(stat -c %Y "$0"); t_main_file=$(stat -c %Y "$p/$main_bn"); \n           if [[ $t_copy_file -gt $t_main_file ]]; then \n               mv "$0" "$p/$main_bn"; \n           else\n               rm "$0"; \n           fi; \n        fi\' {} \\;\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n
    \n
  • p="${0%/*}"- 基本名称被修剪的文件路径/路径
  • \n
  • bn="${0##*/}"- 文件的基本名称
  • \n
  • main_bn="${bn/ (Copy)/}"-(Copy)从基本名称中删除子字符串以获得主/公共基本名称
  • \n
  • if [ -f "$p/$main_bn" ]- 如果主/原始文件存在(并且在符号链接解析后发现是常规文件)\n\n
      \n
    • t_copy_file=$(stat -c %Y "$0")- 获取找到的“复制”文件的最后修改时间
    • \n
    • t_main_file=$(stat -c %Y "$p/$main_bn")- 获取原始文件的最后修改时间
    • \n
    • if [[ $t_copy_file -gt $t_main_file ]]- 如果“复制”文件是最近的文件 - 将其移动到原始文件(使其成为原始文件mv "$0" "$p/$main_bn"
    • \n
    • 否则 -原始文件是最近的文件,删除“复制”文件rm "$0"
    • \n
  • \n
\n\n
\n\n

或者使用文件测试运算符更短一些-nt[ new\xc2\xader\xc2\xadfile \xe2\x80\x93nt olderfile ]- 检查是否newerfile比 更晚更改olderfile,或者是否newerfile存在但olderfile不存在):

\n\n
find . -type f -name "* (Copy).*" -exec bash -c \'p="${0%/*}"; bn="${0##*/}"; \n        main_bn="${bn/ (Copy)/}"; \n        if [ -f "$p/$main_bn" ]; then \n           if [ "$0" -nt "$p/$main_bn" ]; then \n               mv "$0" "$p/$main_bn"; \n           else\n               rm "$0"; \n           fi; \n        fi\' {} \\;\n
Run Code Online (Sandbox Code Playgroud)\n