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

时间:2017-03-31 06:59:55

标签: linux bash shell directory

假设我有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

这是针对2级子目录,是否有更简洁的方法为多层次结构执行此操作?欢迎任何其他一行命令建议/解决方案。

2 个答案:

答案 0 :(得分:0)

当您想在文件/目录中执行递归操作时,有两个选项:

选项1:查找

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

在这种情况下,我们使用find仅使用-type d来返回目录 我们可以要求find仅使用-type f返回文件或不指定任何类型,并且将返回目录和文件。

我们还使用find选项-print0来强制查找结果的空分隔,从而确保在名称包含空格等特殊字符的情况下正确处理名称。

测试:

$ 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

选项2:使用Bash globstar选项

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

在这种情况下,for循环将匹配当前工作目录下的所有子目录(操作**/)。

您也可以要求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

文件夹测试:

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

在您的小脚本中,只需启用shopt -s globstar并将for更改为for dir in **/;do,就可以按预期工作。

答案 1 :(得分:0)

我有一个特定的任务-替换目录和文件中的非ASCII符号和方括号。很好。

首先,以我的情况为例,

find . -depth -execdir rename -v 's/([^\x00-\x7F]+)|([\[\]]+)/\_/g' {} \;

或单独的非ASCII和方括号:

find . -depth -execdir rename -v 's/[^\x00-\x7F]+/\_/g' {} \;
find . -depth -execdir rename -v 's/[\[\]]+/\_/g' {} \;

如果我们只想使用目录,请添加-type d(在-depth选项之后)

现在,在更概括的视图中:

find . -depth [-type d] [-type f] -execdir rename [-v] 's/.../.../g' '{}' \;

在这里,我们可以控制目录/文件和详细程度。在您的计算机上是否可能需要在{}周围加上引号(反斜杠;;之前相同,但可能用引号代替)