如何重命名子目录中的文件?

49

有没有批量重命名子目录中的文件的方法?

例如:

将具有目录和子目录的文件夹中的*.html重命名为*.htm


你所谓的“batch”,是指“一次处理多个任务”还是一种以.bat/.cmd/.sh为扩展名的方式?前者不是一个编程问题,在Windows上有很多免费工具可以实现。后者需要更精确的定义,至少需要知道你要在哪个操作系统上运行。 - PhiLho
11个回答

99

Windows命令提示符:(如果在批处理文件中,请将%x更改为%%x)

for /r %x in (*.html) do ren "%x" *.htm

对于重命名文件中间部分也适用

for /r %x in (website*.html) do ren "%x" site*.htm

2
值得注意的是,这也适用于仅重命名文件的中间部分。因此,如果您所有的文件都以website...开头并以.html结尾,并且您想要将它们重命名为以site开头并更改扩展名,您可以执行以下操作: for /r %x in (website*.html) do ren "%x" site*.htm - jonnybot
Raven,尝试将目录放入双引号中。这应该可以解决你的问题。Linux使用反斜杠转义空格来解决这种情况,我认为Windows也有类似的东西,但我无法确定是哪个字符。 - 猫IT
我需要从文件中删除 .$$$ 扩展名,只需编写以下代码: for /r %x in (*.$$$) do ren "%x" *. - Faraz Ahmed

6
find . -regex ".*html$" | while read line;
 do 
    A=`basename ${line} | sed 's/html$/htm/g'`;
    B=`dirname ${line}`;
    mv ${line} "${B}/${A}";
 done

6

在Python中

import os

target_dir = "."

for path, dirs, files in os.walk(target_dir):
    for file in files:
        filename, ext = os.path.splitext(file)
        new_file = filename + ".htm"

        if ext == '.html':
            old_filepath = os.path.join(path, file)
            new_filepath = os.path.join(path, new_file)
            os.rename(old_filepath, new_filepath)

6

如果您有forfiles(它与Windows XP、2003和更新版本一起提供),则可以运行以下命令:

forfiles /S /M *.HTM /C "cmd /c ren @file *.HTML"

以下是更多使用forfiles的示例:https://www.windows-commandline.com/rename-file-extensions-bulk/ - John Gilmer

5
在Bash中,你可以执行以下操作:
for x in $(find . -name \*.html); do
  mv $x $(echo "$x" | sed 's/\.html$/.htm/')
done

3
In bash use command rename :)

 rename 's/\.htm$/.html/' *.htm

 # or

 find . -name '*.txt' -print0 | xargs -0 rename 's/.txt$/.xml/'

 #Obs1: Above I use regex \. --> literal '.'  and  $ --> end of line
 #Obs2: Use find -maxdepht 'value' for determine how recursive is
 #Obs3: Use -print0 to avoid 'names spaces asdfa' crash!

2

我相信有更加优雅的方法,但这是我脑海中第一个想到的:

for f in $(find . -type f -name '*.html'); do 
    mv $f $(echo "$f" | sed 's/html$/htm/')
done

1

有一个相当强大的forfiles命令:

forfiles /? 可以让你了解该命令可能具备的功能。在这种情况下,它可以用作:

forfiles /S /M *.html /C "cmd /c rename @file @fname.htm"

1
在Linux中,您可以使用“rename”命令来批量重命名文件。

0

在Linux上使用AWK。对于第一个目录,这就是你的答案...通过递归调用dir_path上的awk来推断,也许可以编写另一个awk,它会写下面这个确切的awk...以此类推。

ls dir_path/. | awk -F"." '{print "mv file_name/"$0" dir_path/"$1".new_extension"}' |csh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接