简体   繁体   中英

linux: how to batch rename folder name and the file name under folder

I need a help to finish a script to rename a folders and .

eg: my current folders and files like below:

Gideon/gideon_lisha/Gideon_samuel/Gideon_nathan.xml
Gideon/lisha_gideon/Gideon_noah.xml
...

I want a shell command to rename them like below:

Liang/Liang_lisha/Liang_samuel/Liang_nathan.xml
Liang/lisha_Liang/Liang_noah.xml
...

I tied:

#!/bin/bash

path=$1
filename=$2
newfilename=$3

echo "We are finding '$filename' under the folder '$path'"

count=1

for i in `find $path -iname *$filename*`

do
    newpath=`echo $i | sed "s/$filename/$newfilename/g"`
    sudo mv "$i" "$newpath"
    echo "${count}: Renaming $i to $newpath"
    let count++
done

but the script will stop to:

Liang/gideon_lisha/Gideon_samuel/Gideon_nathan.xml

because it changed the folder name, so that can not find the next path. I do not know how let the script run from inner to outer instead of running outer to inner.

finally, I found out the anwser:

#!/bin/bash

path=$1
filename=$2
newfilename=$3

echo "We are finding '$filename' under the folder '$path'"

count=1
for i in `find $path -iname "*$filename*" | tac`
do
    newpath=`echo $i | sed "s@\(.*\)$filename@\1$newfilename@i"`
    sudo mv "$i" "$newpath"
    echo "${count}: Renaming $i to $newpath"
    let count++
done

really thank @susbarbatus !

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