批量重命名以仅更改单个字符
如何使用 mv 命令将一个目录中的所有文件重命名为新名称。 目录有数千个文件,要求是将每个文件名的最后一个字符更改为某个特定字符。 示例:文件应该
abc.txt
asdf.txt
zxc.txt
...
ab_.txt
asd.txt
更改为
ab_.txt
asd_.txt
zx_.txt
...
ab_.txt
as_.txt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您必须注意名称冲突,但这应该可以正常工作:
在取消注释
mv
之后(我将其注释掉,以便您可以安全地看到它的作用)。 引号用于处理带有空格的文件(在我看来是邪恶的、卑鄙的事情:-)。You have to watch out for name collisions but this should work okay:
after you uncomment the
mv
(I left it commented so you could see what it does safely). The quotes are for handling files with spaces (evil, vile things in my opinion :-).如果所有文件都以“.txt”结尾,您可以使用
mmv
(多次移动):另外:
mmv
会告诉您何时产生碰撞(在您的示例中) :abc.txt 变为 ab_.txt(在重命名任何文件之前已经存在)。请注意,您必须引用文件名,否则 shell 将在
mmv
看到列表之前展开该列表(但mmv
通常也会捕获此错误)。If all files end in ".txt", you can use
mmv
(Multiple Move) for that:Plus:
mmv
will tell you when this generates a collision (in your example: abc.txt becomes ab_.txt which already exists) before any file is renamed.Note that you must quote the file names, else the shell will expand the list before
mmv
sees it (butmmv
will usually catch this mistake, too).如果您的文件都有 .txt 后缀,我建议使用以下脚本:
If your files all have a .txt suffix, I suggest the following script:
是否明确要求您使用
mv
命令?perl
rename
实用程序就是为此类事情编写的。 这是基于 debian 的 Linux 发行版的标准,但根据 此页面它可以很容易地添加到任何其他页面。如果它已经存在(或者如果您安装了它),您可以执行以下操作:
上面包含的页面包含有关正则表达式的一些基本信息以及需要的内容。
Is it a definite requirement that you use the
mv
command?The perl
rename
utility was written for this sort of thing. It's standard for debian-based linux distributions, but according to this page it can be added really easily to any other.If it's already there (or if you install it) you can do:
The page included above has some basic info on regex and things if it's needed.
Find 应该比
for file in *.txt
更高效,后者会将所有 1000 个文件扩展为一长串命令行参数。 示例(更新为使用 bash 替换方法):Find should be more efficient than
for file in *.txt
, which expands all of your 1000 files into a long list of command line parameters. Example (updated to use bash replacement approach):我不确定这是否适用于数千个文件,但在 bash 中:
I'm not sure if this will work with thousands of files, but in bash:
您可以这样使用 bash 的
${parameter%%word}
运算符:You can use bash's
${parameter%%word}
operator thusly: