【问题标题】:Batch Renaming multiple files with different extensions Linux Script?批量重命名具有不同扩展名Linux脚本的多个文件?
【发布时间】:2013-03-13 04:49:17
【问题描述】:

我想编写一个 linux 脚本,它将所有具有相同文件名(但扩展名不同)的文件移动或复制到所有这些文件的新文件名,同时保持它们不同的扩展名。换句话说:

如果我从目录列表开始:

file1.txt, file1.jpg, file1.doc, file12.txt, file12.jpg, file12.doc

我想编写一个脚本来更改所有文件名而不更改扩展名。对于同一示例,选择 file2 作为新文件名,结果将是:

file2.txt, file2.jpg and file2.doc, file12.txt, file12.jpg, file12.doc

因此文件名与当前条件不匹配的文件不会被更改。

祝你好运,

乔治

【问题讨论】:

  • 为什么 file2 匹配 file1 而不是 file12 ?同名长度,以一位数字结尾?

标签: linux shell scripting batch-rename


【解决方案1】:

util-linux-ng 软件包(大多数 linux 版本默认安装它)具有命令“重命名”。使用说明见man rename。使用它,您的任务可以简单地完成

rename file1 file2 file1.*

【讨论】:

    【解决方案2】:

    要处理基本名称包含特殊字符的输入文件,我会将 plesiv 的脚本修改为以下内容:

    if [ $# -ne 2 ]; then
        echo "Two arguments required."
        exit;
    fi
    
    for i in "$1".*; do
        if [ -e "$i" ]; then
            mv "$i" "$2.${i##*.}"
            echo "$i to $2.${i##*.}";
        fi
    done
    

    注意 $1 周围的额外引号。

    【讨论】:

      【解决方案3】:

      注意:如果变量i 中有file1.doc,则表达式${i##*.} 提取扩展名,即在这种情况下为doc


      一线解决方案:

      for i in file1.*; do mv "$i" "file2.${i##*.}"; done
      

      脚本:

      #!/bin/sh
      # first argument    - basename of files to be moved
      # second arguments  - basename of destination files
      if [ $# -ne 2 ]; then
          echo "Two arguments required."
          exit;
      fi
      
      for i in $1.*; do
          if [ -e "$i" ]; then
              mv "$i" "$2.${i##*.}"
              echo "$i to $2.${i##*.}";
          fi
      done
      

      【讨论】:

      • 感谢您的建议。不幸的是,filename1 在脚本运行时是未知的。我正在处理数百个文件夹,其中将有 6 个文件,其中 3 个具有相同的文件名(可变的数字和字母列表),但有 3 个不同的扩展名。每个文件夹中只有 2 个文件名。示例:文件夹 1 包含:filetextwords12.gif、filetextwords12.jpg、filetextwords12.txt、filextwordste23.gif、filextwordste23.jpg、filextwordste23.txt。 Folder2 将包含类似的设置(2 个文件名,每个文件名 3 种不同的文件类型)。谢谢! GH
      • 程序应该如何知道是更改filetextwords12 还是filetextwordste23 文件? filetextwordste23 是否也应该以 filetextwords12 应该的类似方式移动?如果您能详细说明一下,也许我们可以帮助您...
      猜你喜欢
      • 2012-11-13
      • 1970-01-01
      • 2014-06-16
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 2015-12-12
      • 2013-03-12
      相关资源
      最近更新 更多