How to rename all directories , files and text in the files recursively using bash shell script in linux

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to rename all directories , files and text in the files recursively using bash shell script in linux on this date .

i have rename all files and text in files and also should rename directories to the deepest level and it has to be done recursively i tried below two codes:

code :

#!/bin/bash
cd /home/my_codes/vehicle

echo "enter the old name: "
read old_name
echo "enter the new name: "
read new_name
    echo "you entered $old_name and $new_name "

if [[ $old_name -eq $new_name ]]; then 
 #i have tried with "$old_name" == "$new_name" but no use
   echo "redeclaration error"
else
echo "process started"
for f in *;
do
sed -i 's/$old_name/$new_name/' "$f"
if cmp -s -- "$f" $old_name*.txt; then
        mv "$f" "${f/$old_name/$new_name}"
fi 
done
fi

the code is always returning redeclaration error even if i give it different names. the functionality is working fine without first if condition but i just added to check it with the arguments and redeclaration error.

edit : i have tried with the following recursive code but unable to do it. please let me know what changes i can make in same code to get the desired output.

#!/bin/bash
rnrr() {
   
      echo "processing"
      echo $old_name
      echo $new_name
    for f in *;
    do
        if [ -d "$f" ]; then
           mv  "$f" "${f/$old_name/$new_name}"
           echo $f
           rnrr "$f"/*
     else 
           sed -i "s/$old_name/$new_name/" "$f"
                if cmp -s -- "$f" $old_name.*; then
                           mv "$f" "${f/$old_name/$new_name}"
            fi
            
         fi
     shift
     done


}
echo " current directory :"
currdir=$(pwd)
echo $currdir   
echo "enter the diretory path(absolute):"
read path
cd $path

echo "current directory :"
echo $(pwd)
echo "enter the old name :"
read old_name    
echo "enter the new name :"
read new_name
echo "process started.."

rnrr 

Answer

Can be easily achieved with find sed and rename command First lets replace the all vehicle with car in all txt/.c file content using following command which uses sed substitution

find -name vehicle.txt -exec sed -i "s:vehicle:car:g" {} ;

Now lets rename file and folders name using following command

find -depth -name "vehicle*" -exec rename "s/(.*)vehicle/1car/" {} +

Notice that i have added -depth in final command to make sure deepest folder/file is renamed first. Please refer man pages for find,sed and rename for more info