如何在 Unix/Linux 中为文件夹中的所有文件添加 .xml 扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7253198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:58:19  来源:igfitidea点击:

How to add .xml extension to all files in a folder in Unix/Linux

phppythonlinuxshellunix

提问by aWebDeveloper

I want to rename all files in a folder and add a .xmlextension. I am using Unix. How can I do that?

我想重命名文件夹中的所有文件并添加.xml扩展名。我正在使用 Unix。我怎样才能做到这一点?

采纳答案by Roshan Mathews

On the shell, you can do this:

在外壳上,您可以执行以下操作:

for file in *; do
    if [ -f ${file} ]; then
        mv ${file} ${file}.xml
    fi
done

Edit

编辑

To do this recursively on all subdirectories, you should use find:

要在所有子目录上递归执行此操作,您应该使用find

for file in $(find -type f); do
    mv ${file} ${file}.xml
done

On the other hand, if you're going to do anything more complex than this, you probably shouldn't use shellscripts.

另一方面,如果您要做比这更复杂的事情,您可能不应该使用shell脚本。

Better still

更好的是

Use the comment provided by Jonathan Lefflerbelow:

使用下面Jonathan Leffler提供的评论:

find . -type f -exec mv {} {}.xml ';'

回答by Eli Bendersky

In Python:

Python 中

Use os.listdirto find names of all files in a directory. If you need to recursivelyfind all files in sub-directories as well, use os.walkinstead. Its API is more complex than os.listdirbut it provides powerful ways to recursively walk directories.

使用os.listdir查找所有文件的名称在目录中。如果您还需要递归查找子目录中的所有文件,请os.walk改用。它的 API 比os.listdir它更复杂,但它提供了递归遍历目录的强大方法。

Then use os.renameto rename the files.

然后使用os.rename重命名文件。

回答by mario

Don't know if this is standard, but my Perlpackage (Debian/Ubuntu) includes a /usr/bin/prename(and a symlink just rename) which has no other purpose:

不知道这是否是标准的,但我的Perl包(Debian/Ubuntu)包含一个/usr/bin/prename(和一个符号链接rename),它没有其他用途:

rename 's/$/.xml/' *

回答by Rob?

find . -type f \! -name '*.xml' -print0 | xargs -0 rename 's/$/.xml/'