仅重命名唯一文件

时间:2019-12-18 14:31:45

标签: shell sh rename

如何通过从文件名中删除“ 1”来仅重命名唯一文件并保留重复的名称文件?

输入:

-english_1.pdf  
-english_2.pdf  
-english_3.pdf  
-mathematics_1.pdf  
-theology_1.pdf  
-economics_1.pdf  
-economics_2.pdf

如何使用或类似的内容从mathematics_1.pdf和theology_1.pdf中删除 1

所需的输出

-english_1.pdf  
-english_2.pdf  
-english_3.pdf  
-mathematics.pdf  
-theology.pdf  
-economics_1.pdf  
-economics_2.pdf

我尝试过:

rename -n  's/1//' *.pdf

但会删除 all 1

1 个答案:

答案 0 :(得分:5)

安全下注可能是以下方法:

for file in *_1.pdf; do
   [ -f "${file/_1.pdf/_2.pdf}" ] || mv "${file}" "${file/_1.pdf/.pdf}"
done

它的作用如下:

  • for file in *_1.pdf; do ... done在所有与全局模式*_1.pdf匹配的文件上循环。因此,它匹配所有看起来像prefix_1.pdf
  • 的文件
  • [ -f "${file/_1.pdf/_2.pdf}" ]:循环中的第一件事是验证是否存在名称为prefix_2.pdf的相似文件。我们使用扩展名

    获取该文件名。
      

    ${parameter/pattern/string}模式替换。像路径名扩展一样,pattern被扩展以生成模式,参数被扩展,pattern与它的值的最长匹配被替换为string

         

    来源:man bash

    写为test的{​​{1}}命令检查是否存在带有[ -f filename ]的文件。有关更多信息,请参见filename

  • 如果以上测试成功,我们什么也不做。如果上述测试失败,则使用man test重命名原始文件。此条件组合是通过使用OR列表实现的:

      

    或列表的形式为 mv "${file}" "${file/_1.pdf/.pdf}" command1 || command2仅在command2返回非零退出状态时执行。

         

    来源:command1

我在这里假设man bash存在时文件prefix_2.pdf必须存在。

您可以通过在prefix_3.pdf命令之前添加echo来验证上述内容。