根据文件夹名称重命名文件

根据文件夹名称重命名文件

我有许多index.html文件存放在具有唯一名称的文件夹中(每个文件夹一个文件)。我希望将每个文件重命名为其父文件夹的名称。

从:

/folder1/index.html
/folder2/index.html
/folder3/index.html
/folder4/index.html
/folder5/index.html

到:

/folder1/folder1.html
/folder2/folder2.html
/folder3/folder3.html
/folder4/folder4.html
/folder5/folder5.html

尝试 1

我已尝试,rename -vn 's:(/[^/]*)/[^/]*$:$1$1.html:' folder/*/*.html返回结果为:

Using expression: sub { use feature ':5.18'; s:(/[^/]*)/[^/]*$:$1$1.html: }
'folder/*/*.html' unchanged

我不太明白到底发生了什么,如何才能修复它。

第二次尝试

接下来,我尝试了rename -n -v '...' folder/*/*.html,结果返回:

Using expression: sub { use feature ':5.18'; ... }
Unimplemented at (eval 2) line 1.

我使用 OSX改名已安装。

答案1

这对我行得通:

rename -vn 's/([^\/]+)\/index/$1\/$1/' folder*/*.html

印刷:

folder1/index.html renamed as folder1/folder1.html
folder2/index.html renamed as folder2/folder2.html
folder3/index.html renamed as folder3/folder3.html
folder4/index.html renamed as folder4/folder4.html
folder5/index.html renamed as folder5/folder5.html

另一个解决方案是sed

ls -1 folder*/*.html | sed 's/\([^\/]\+\)\/index.html/mv "\0" "\1\/\1.html"/'

印刷:

mv "folder1/index.html" "folder1/folder1.html"
mv "folder2/index.html" "folder2/folder2.html"
mv "folder3/index.html" "folder3/folder3.html"
mv "folder4/index.html" "folder4/folder4.html"
mv "folder5/index.html" "folder5/folder5.html"

如果打印出正确的命令,只需将其通过管道传输到bash。但在执行之前,首先确保打印的命令可以正常工作:

ls -1 folder*/*.html | sed 's/\([^\/]\+\)\/index.html/mv "\0" "\1\/\1.html"/' | bash

答案2

您可以尝试以下方法:

for in in `find . -name index.html -type f`
do
bname=$(dirname $i|sed 's:/::g')
mv $i $(dirname $i)/${bname}.html
done

PS 这只适用于一级目录和扩展名为 .html 的文件

相关内容