简体   繁体   English

如何在Linux中递归重命名目录和子目录?

[英]How to rename directory and subdirectories recursively in linux?

Let say I have 200 directories and it have variable hierarchy sub-directories, How can I rename the directory and its sub directories using mv command with find or any sort of combination? 假设我有200个目录,并且它具有可变的层次结构子目录,如何使用带有find或任何组合的mv命令重命名目录及其子目录?

for dir in ./*/; do (i=1; cd "$dir" && for dir in ./*; do printf -v dest %s_%02d "$dir" "$((i++))"; echo mv "$dir" "$dest"; done); done

This is for 2 level sub directory, is there more cleaner way to do it for multiple hierarchy? 这是2级子目录,是否有更简洁的方法可用于多个层次结构? Any other one line command suggestions/ solutions are welcome. 欢迎任何其他一行命令建议/解决方案。

You have two options when you want to do recursive operations in files/directories: 要在文件/目录中执行递归操作时,有两种选择:

Option 1 : Find 选项1:查找

while IFS= read -r -d '' subd;do
  #do your stuff here with var $subd
done < <(find . -type d -print0)

In this case we use find to return only dirs using -type d 在这种情况下,我们使用find -type d只返回目录
We can ask find to return only files using -type f or not to specify any type and both directories and files will be returned. 我们可以要求find仅返回使用-type f文件,或者不指定任何类型,并且目录和文件都将被返回。

We also use find option -print0 to force null separation of the find results and thus to ensure correct names handling in case names include special chars like spaces, etc. 我们还使用find选项-print0强制将查找结果分隔为空,从而确保在名称包含特殊字符(例如空格等)的情况下正确处理名称。

Testing: 测试:

$ while IFS= read -r -d '' s;do echo "$s";done < <(find . -type d -print0)
.
./dir1
./dir1/sub1
./dir1/sub1/subsub1
./dir1/sub1/subsub1/subsubsub1
./dir2
./dir2/sub2

Option 2 : Using Bash globstar option 选项2:使用Bash globstar选项

shopt -s globstar
for subd in **/ ; do
  #Do you stuff here with $subd directories
done

In this case , the for loop will match all subdirs under current working directory (operation **/ ). 在这种情况下,for循环将匹配当前工作目录(操作**/ )下的所有子目录。

You can also ask bash to return both files and folders using 您也可以要求bash使用以下命令返回文件和文件夹

for sub in ** ;do #your commands;done
  if [[ -d "$sub" ]];then 
      #actions for folders
  elif [[ -e "$sub" ]];then
      #actions for files
  else
     #do something else
  fi
done

Folders Test: 文件夹测试:

$ shopt -s globstar
$ for i in **/ ;do echo "$i";done
dir1/
dir1/sub1/
dir1/sub1/subsub1/
dir1/sub1/subsub1/subsubsub1/
dir2/
dir2/sub2/

In your small script, just by enabling shopt -s globstar and by changing your for to for dir in **/;do it seems that work as you expect. 在您的小脚本中,只需启用shopt -s globstarfor dir in **/;do更改为for dir in **/;do可以按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM