Search code examples
unixrenamekshmvhp-ux

renaming the files recursively in unix


i know this would be marked as a duplicate one, but i tried searching google and what i'm trying is not working for me.

I've some .txt files in a directory, i need to rename all the *.txt files to *_XYZ.txt recursively. XYZ is defined in a variable X.

I've tried below code:

file=`find ./ -type f -name "*.txt"|sed "s,^./,,g" |awk -F '.' '{print $1}'`

for i in "$file"
do
mv "$i" "$i_${X}.txt"
done

Any help would be greatly appreciated. Thanks.


Solution

  • Your script destroys original filenames in variable file, this is why it cannot rename files.

    Working example:

    X="_XYZ"
    for f in $(find . -type f ! -name "*$X.txt" -name "*.txt"); do 
        mv "$f" "${f%.txt}$X.txt"
    done
    

    Output:

    $ X="_XYZ"
    $ find . -type f -name "*.txt"
    ./c_XYZ.txt
    ./aa/c.txt
    ./a.txt
    ./b.txt
    $ for f in $(find . -type f ! -name "*$X.txt" -name "*.txt"); do mv "$f" "${f%.txt}$X.txt"; done
    $ find . -type f -name "*.txt"
    ./b_XYZ.txt
    ./c_XYZ.txt
    ./aa/c_XYZ.txt
    ./a_XYZ.txt