简体   繁体   中英

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.

I want to put an if statement around the mv that says if the filename contains RELEASE in it then carry on. If I do not have this if statement I get errors saying

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 file in *RELEASE*.clu
do
    mv -f "$file" "${file//RELEASE/$1}"
done

Even better, use the rename command if you have it:

rename RELEASE "" *RELEASE*.clu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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