简体   繁体   English

替换bash中文件名中的字符串

[英]Replace string in filename in bash

So I have this function 所以我有这个功能

ren_barrow(){
    for file in *.clu
    do
        mv -f $file ${file//RELEASE/"$1"}
    done
}

but when I run this, as you can see everyfile that ends in .clu will be renamed. 但是当我运行此文件时,如您所见,每个以.clu结尾的文件都会被重命名。

I want to put an if statement around the mv that says if the filename contains RELEASE in it then carry on. 我想在mv周围放一个if语句,说如果文件名中包含RELEASE,然后继续。 If I do not have this if statement I get errors saying 如果我没有这个if陈述,则会收到错误讯息:

Cannot rename: $file and $file is the same file.

ren_barrow(){
    for file in *.clu
    do
        # if $file grep "RELEASE"; then
            mv -f $file ${file//RELEASE/"$1"}
        # fi
    done
}

您可以使用如下的mv命令:

[[ "$file" != *"RELEASE"* ]] && mv -f "$file" "${file//RELEASE/$1}"

Why not change your for loop so that you don't have to iterate over all the files? 为什么不更改for循环,以使您不必遍历所有文件?

for file in *RELEASE*.clu
do
    mv -f "$file" "${file//RELEASE/$1}"
done

Even better, use the rename command if you have it: 更好的是,如果有,请使用rename命令:

rename RELEASE "" *RELEASE*.clu

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

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