2013-03-23 35 views
3

我想编写一个linux脚本,将所有文件的文件名(但扩展名不同)的所有文件移动或复制到所有这些文件的新文件名,同时保留其不同的扩展名。换句话说:批处理使用不同的扩展名重命名多个文件Linux脚本?

如果我开始有一个目录列表:

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

我想编写一个脚本来改变所有的文件名不改变扩展。对于同样的例子,选择文件2为新的文件名中的结果将是:

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

所以其文件的文件不符合目前的标准不会改变。

最良好的祝愿,

乔治

+0

'file1 *'+ loop – 2013-03-23 10:03:23

+0

为什么file2匹配file1而不是file12?相同的名字长度,以一位数字结尾? – PeterMmm 2013-03-23 10:06:26

回答

4

注:如果有变量ifile1.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 
+0

谢谢你的建议。不幸的是,脚本运行时filename1是未知的。我正在处理数百个文件夹,其中有6个文件,其中3个具有相同的文件名(可变数字和字母列表),但有3个不同的扩展名。在每个文件夹中只有2个文件名。示例:Folder1包含:filetextwords12.gif,filetextwords12.jpg,filetextwords12.txt,filextwordste23.gif,filextwordste23.jpg,filextwordste23.txt。 Folder2将包含一个类似的设置(每个文件类型3个不同的文件名)。谢谢! GH – 2013-03-23 16:16:09

+0

程序如何知道是要更改'filetextwords12'还是'filetextwordste23'文件? 'filetextwordste23'也应该以'filetextwords12'类似的方式移动?如果你可以详细说明一下,也许我们可以帮助你... – plesiv 2013-03-24 11:07:13

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附近的额外引号。

2

util-linux-ng软件包(大多数Linux版本都默认安装了)包含命令'rename'。有关使用说明,请参阅man rename。使用它你的任务可以这样简单

rename file1 file2 file1.*

相关问题