简体   繁体   English

批量重命名具有不同扩展名Linux Script的多个文件?

[英]Batch Renaming multiple files with different extensions Linux Script?

I would like to write a linux script that will move or copy all files with the same filename (but different extensions) to a new filename for all those files, while maintaining their different extensions. 我想编写一个linux脚本,将所有文件移动或复制到具有相同文件名(但扩展名不同)的文件到所有这些文件的新文件名,同时保持不同的扩展名。 In other words: 换一种说法:

if I start with a directory listing: 如果我从目录列表开始:

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

I would like to write a script to change all the filenames without changing the extensions. 我想编写一个脚本来更改所有文件名而不更改扩展名。 For the same example, choosing file2 as the new filename the result would be: 对于同一示例,选择file2作为新文件名,结果将是:

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

So the files whose filename do not match the current criteria will not be changed. 因此,不会更改其文件名与当前条件不匹配的文件。

Best wishes, 最好的祝愿,

George 乔治

Note: If there's file1.doc in variable i , expression ${i##*.} extracts extension ie doc in this case. 注意:如果变量ifile1.doc ,则表达式${i##*.}在这种情况下提取扩展名即doc


One line solution: 一线解决方案:

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

The util-linux-ng package (most of linux flavours have it installed by default) has the command 'rename'. util-linux-ng软件包(大多数linux风格默认安装它)都有命令'rename'。 See man rename for use instructions. 请参阅man rename以获取使用说明。 Using it your task can be done simply as that 使用它,您的任务可以简单地完成

rename file1 file2 file1.*

To handle input files whose basenames contain special characters, I would modify plesiv's script to the following: 要处理基本名称包含特殊字符的输入文件,我会将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

Note the extra quotes around $1. 请注意1美元左右的额外报价。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM