简体   繁体   中英

Shell script to rename multiple files from their parent folders

I'm looking for a script for below structure:

Before :

/Description/TestCVin/OpenCVin/NameCv/.....
/Description/blacVin/baka/NameCv_hubala/......
/Description/CVintere/oldCvimg/NameCv_add/.....

after:

/Description/TestaplCVin/OpenaplCVin/NameaplCv/.....
/Description/blaapcVlin/baka/NameaplCv_hubala/......
/Description/aplCVintere/oldaplCvimg/NameaplCv_add/.....

I want to rename " Cv or CV or cV " >> "aplCv or aplCV or aplcV" in all folder by regular expression...

My script does look like:

#!/bin/sh

printf "Input your Directory path: -> "

read DIR

cd "$DIR"

FILECASE=$(find . -iname "*cv*")

LAST_DIR_NAME=""

for fdir in $FILECASE
do
        if [[ -d $fdir ]];
        then
            LAST_DIR_NAME=$fdir

        fi

        FILE=$(echo $fdir | sed -e "s/\([Cc][Vv]\)/arpl\1/g")
        echo "la file $FILE"
        if ([[ -f $fdir ]] && [[ "$fdir" =~ "$LAST_DIR_NAME" ]]);
        then
           FILECASE=$(find . -iname "*cv*")

            tmp=$(echo $LAST_DIR_NAME | sed -e "s/\([Cc][Vv]\)/arpl\1/g")
            fdir=$(echo $fdir | sed -e 's|'$LAST_DIR_NAME'|'$tmp'|g')
        fi

        mv -- "$fdir" "$FILE"
done

But it throws an error ..:(

How could I write it to rename the files according to their folder names?

Always make a backup before playing with this kind of scripts.

You can try the following:

find . -iname '*cv*' -exec echo 'mv {} $(echo $(dirname {})/$(basename {}|sed s/cv/apl/gi))' \;|tac|xargs -i bash -c 'eval {}'

This uses -exec to print commands for renaming. The second arguments are generated by using shell substitutions to replace cv with apl in the last part of the path. tac is used to reverse the order of the commands, so that we do not rename a directory before working with its contents. Finally, we eval the commands with bash.

Also, do not use -exec in a permanent script. Please read the security warnings about exec in the find man-page.

You can do like this

#!/bin/sh

printf "Input your Directory path: -> "
read DIR
cd "$DIR"
MYARRAY=$(find . -iname "*cv*" )

touch "tmpfile"

for fdir in $MYARRAY
do
    echo "$fdir" >> "tmpfile"
done

MYARRAY=$(tac "tmpfile")

for fdir in $MYARRAY
do
    cd "$fdir"
    prev=$(cd -) 
    base=$(basename $fdir)
    cd ..
    nDIR=$(echo "$base" | sed -e "s/\([Cc][Vv]\)/arpl\1/g") 
    mv "$base" "$nDIR"
    cd $prev    
done

rm -f "tmpfile"

Also one issue i think tac command not included in Mac OS X.Instead tac use tail -r like MYARRAY=$(tail -r "tmpfile")

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