Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在linux中使用bash shell脚本递归重命名文件中的所有目录、文件和文本_Linux_Bash_Shell_Scripting - Fatal编程技术网

如何在linux中使用bash shell脚本递归重命名文件中的所有目录、文件和文本

如何在linux中使用bash shell脚本递归重命名文件中的所有目录、文件和文本,linux,bash,shell,scripting,Linux,Bash,Shell,Scripting,我已经重命名了文件中的所有文件和文本,还应该将目录重命名到最深的级别,并且必须递归完成。我尝试了以下两个代码: 代码: #!/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_n

我已经重命名了文件中的所有文件和文本,还应该将目录重命名到最深的级别,并且必须递归完成。我尝试了以下两个代码:

代码:

#!/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
代码总是返回重新声明错误,即使我给它不同的名称。该功能在没有第一个if条件的情况下运行良好,但我只是添加了参数和重新声明错误来检查它

编辑: 我已经尝试了下面的递归代码,但无法做到这一点。请让我知道我可以在相同的代码中进行哪些更改以获得所需的输出

#!/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 

可以通过findsed和rename命令轻松实现 首先,让我们使用以下使用sed替换的命令将所有txt/.c文件内容中的所有车辆替换为car

find -name vehicle.txt -exec sed -i "s:vehicle:car:g" {} \;
现在让我们使用以下命令重命名文件和文件夹名称

find -depth -name "vehicle*" -exec rename "s/(.*)vehicle/\1car/" {} +
请注意,我在final命令中添加了-depth,以确保首先重命名最深的文件夹/文件。
有关更多信息,请参阅“查找、搜索和重命名”手册页

查看“不提示输入参数”。而是
old_name=${1};new_name=${2}
您发布的解决方案无法递归运行。请尝试[[“$old_name”=“$new_name”]]了解我是否编辑了问题并更新了新代码。请您建议对上述代码中的问题陈述进行必要的更正,并感谢您的解决方案,但任务是编写一个没有find的递归函数。