如何使用 Perl 轻松批量重命名文件?
我有很多文件正在尝试重命名,我尝试创建一个正则表达式来匹配它们,但即使如此,我仍然卡在文件的命名上,如下所示:
文件名01
文件名100
文件名02
文件名03
等等,我想在任何小于 100 的文件后面添加一个“0”(零),如下所示:
文件名001
文件名100
文件名002
文件名003
我最接近匹配它们的是使用这个 find -type d |排序-r | grep ' [1-9][0-9]$' 但是我不知道如何替换它们。预先感谢您可以为我提供的任何帮助。我使用的是 CentOS,如果这有帮助的话,所有这些都是通过 SSH 完成的。
I have a lot of files I'm trying to rename, I tried to make a regular expression to match them, but even that I got stuck on the files are named like:
File Name 01
File Name 100
File Name 02
File Name 03
etc, I would like to add a "0" (zero), behind any of file that are less than 100, like this:
File Name 001
File Name 100
File Name 002
File Name 003
The closest I got to so much as matching them was using this find -type d | sort -r | grep ' [1-9][0-9]$' however I could not figure out how to replace them. Thanks in advance for any help you can offer me. Im on CentOS if that is of any help, all this is being done via SSH.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
也许有点矫枉过正,但它确实满足了要求。
A bit overkill maybe, but it does what is asked.
或类似的东西,前提是
-print0
和-0
)or something like that, provided
-print0
and-0
)这是一次性的事情吗?如果是这样,我将建议一些可能被许多程序员逃避的东西:
通过管道传输命令的输出 (
find -type d | sort -r | grep ' [1-9][ 0-9]$'
)到一个文件,并使用编辑器和一些全局搜索/替换魔法来创建一个执行重命名的脚本。然后把剧本扔掉。
没有什么大惊小怪的,也很少有可能你会因为尝试一种聪明的(但调试不充分的)单行代码而导致文件中的杂草丛生,最终搬起石头砸自己的脚。
Is this a one-time thing? If so, I'm going to suggest something that might seem to be a cop out by many programmers here:
Pipe the output of your command (
find -type d | sort -r | grep ' [1-9][0-9]$'
) to a file and use an editor along with some global search/replace magic to create a script that does the renames.Then throw away the script.
There's little fuss and little chance that you'll end up shooting yourself in the foot by having some attempt at a clever (but inadequately debugged) one-liner go off into the weeds on your files.
按以下顺序运行两个命令:
第一个命令重命名小于 10 的所有内容并在前面添加零。第二个重命名所有小于 100 的内容并在前面添加一个零。所有文件名的结果都应该是三位数。
Run two commands, in this order:
First one renames everything less than 10 and prepends a zero. The second one renames everything less than 100 and prepends a zero. The result should be three digits for all filenames.
在我的 debian 中,它可以很好地进行重命名,并使用 300 个文件进行了测试。
In my debian it works well with rename, tested with 300 files.
我认为 mmv 是你的朋友。
I think mmv is your friend here.
你可以使用 perl 或 ruby 做一些事情。
将所有这些文件放在同一目录中
you could do something using perl or ruby.
put all this files in the same directory
如果您的遥控器有 bash shell,
请删除“echo”以进行实际重命名
if your remote has bash shell
remove "echo" to do actual renaming