如何在 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
How to add .xml extension to all files in a folder in Unix/Linux
提问by aWebDeveloper
I want to rename all files in a folder and add a .xml
extension. 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 shell
scripts.
另一方面,如果您要做比这更复杂的事情,您可能不应该使用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.listdir
to find names of all files in a directory. If you need to recursivelyfind all files in sub-directories as well, use os.walk
instead. Its API is more complex than os.listdir
but it provides powerful ways to recursively walk directories.
使用os.listdir
查找所有文件的名称在目录中。如果您还需要递归查找子目录中的所有文件,请os.walk
改用。它的 API 比os.listdir
它更复杂,但它提供了递归遍历目录的强大方法。
Then use os.rename
to rename the files.
然后使用os.rename
重命名文件。
回答by mario
Don't know if this is standard, but my Perl
package (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/'