简体   繁体   English

正则表达式使用 rename linux 命令重命名文件名

[英]Regex rename a filename using rename linux command

I am trying to rename a file first_second.pdf into first_0second.pdf我正在尝试将文件 first_second.pdf 重命名为 first_0second.pdf

So, I read about capturing and back reference.因此,我阅读了有关捕获和反向引用的信息。 But somehow it doesnt work.但不知何故它不起作用。 Can anyone tell me what I am doing wrong?谁能告诉我我做错了什么?

rename 's/\(.*_\)\([1-9]\).pdf$/$10$2.pdf/' first_1.pdf

I am expecting first_1.pdf to renamed to first_01.pdf我期待 first_1.pdf 重命名为 first_01.pdf

The -n argument shows you what it is going to do without actually doing it which is good for testing. -n参数向您展示了它将要做什么,而无需实际执行它,这对测试有好处。 Match and capture the first part up to and including the underscore.匹配并捕获第一部分直到并包括下划线。 Then match and capture 1 or more numbers followed by the literal dot and anything else until the end of the line.然后匹配并捕获 1 个或多个数字,后跟文字点和其他任何内容,直到行尾。 Replace with the first captured group (braces around the group number in order to separate it from the literal '0'), a literal '0', then the 2 remaining captured groups.替换为第一个捕获的组(组号周围的大括号以将其与文字“0”分开),文字“0”,然后是剩余的 2 个捕获组。

rename -n 's/(.*_)([0-9]+)(\..*)$/${1}0$2$3/' first_1.pdf

rename(first_1.pdf, first_01.pdf)

The problem was the escape character and the curly brackets surrouding the back references.问题是转义字符和围绕后引用的大括号。 This is because rename internally uses posix-extended.这是因为重命名在内部使用 posix-extended。 Escape character would have been necessary, if rename had used posix-basic as regextype.如果重命名使用 posix-basic 作为 regextype,则需要转义字符。

By removing the escapes and adding curly brackets for the back references, the regex expression worked.通过删除转义并为反向引用添加大括号,正则表达式起作用了。

rename 's/(.*_)([1-9]).pdf$/${1}0${2}.pdf/' first_1.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM