使用Linux脚本进行批量重命名具有不同扩展名的多个文件?

7
我想编写一个Linux脚本,将所有具有相同文件名(但扩展名不同)的文件移动或复制到新文件名中,同时保留它们的不同扩展名。换句话说:
如果我开始列出一个目录列表:
file1.txt、file1.jpg、file1.doc、file12.txt、file12.jpg、file12.doc
我想编写一个脚本来更改所有文件名而不更改扩展名。对于同样的例子,选择file2作为新文件名,结果将是:
file2.txt、file2.jpg和file2.doc、file12.txt、file12.jpg、file12.doc
因此,文件名不匹配当前标准的文件将不会被更改。

为什么file2与file1匹配,但不与file12匹配?名称长度相同,以一个数字结尾? - PeterMmm
3个回答

8
注意:如果变量i中有file1.doc,则表达式${i##*.}提取其扩展名,即在本例中为doc
一行解决方案:
for i in file1.*; do mv "$i" "file2.${i##*.}"; done

Script:

#!/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个文件名。例如:Folder1包含:filetextwords12.gif,filetextwords12.jpg,filetextwords12.txt,filextwordste23.gif,filextwordste23.jpg,filextwordste23.txt。Folder2将包含类似的设置(每种文件类型有2个文件名)。谢谢!GH - George Hadley
程序应该如何知道是更改 filetextwords12 还是 filetextwordste23 文件呢?是否应该以类似更改 filetextwords12 的方式移动 filetextwordste23?如果您能再详细说明一些,也许我们可以帮助您... - plesiv

4

util-linux-ng包(大多数Linux发行版默认安装)有一个命令叫做“rename”。请参见man rename以获取使用说明。使用它,您的任务可以简单地完成如下:

rename file1 file2 file1.*


0
为了处理包含特殊字符的文件名,我会修改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周围的额外引号。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接