I’m using a GNU/Linux distribution where the utility rename
comes from util-linux
and I want to make full use of regular (Perl or POSIX) expressions with it.
我使用的是GNU/Linux发行版,该实用程序重命名来自util-linux,我希望充分利用其中的正则(Perl或POSIX)表达式。
There are two versions of rename
:
重命名有两个版本:
- The “Perl” version, with syntax
rename 's/^fgh/jkl/' fgh*
- “Perl”版本,语法重命名的s / ^ fgh / . jkl的fgh *
- The
util-linux
version, with syntaxrename fgh jkl fgh*
- 使用语法重命名fgh jkl fgh*的util-linux版本
If the use of regexes seems pretty obvious with the first one, to which I have no easy access. However, I’m confused about the second one: I could not find any relevant documentation or examples on the possible use, and in that case the format, of the regular expressions to use.
如果在第一个例子中regexe的使用看起来非常明显,我无法轻松访问第一个例子。但是,我对第二个问题感到困惑:我找不到关于可能使用的正则表达式的任何相关文档或示例,在这种情况下,也找不到要使用的正则表达式的格式。
Let’s take, to make a simple example, a directory containing:
我们来举一个简单的例子,一个包含以下内容的目录:
foo_a1.ext
foo_a32.ext
foo_c18.ext
foo_h12.ext
I want to use a syntax like one of these two lines:
我想使用一种语法,就像这两行:
rename "foo_[a-z]([0-9]{1,2}).ext" "foo_\1.ext" *
rename "foo_[:alpha:]([:digit:]{1,2}).ext" "foo_\1.ext" *
for which the expected output would be:
预期产出为:
foo_1.ext
foo_32.ext
foo_18.ext
foo_12.ext
Of course this does not work! Either I’m missing something obvious, or there is no implemented way to use actual regular expressions with this tool.
当然这行不通!或者我遗漏了一些明显的东西,或者没有实现的方法来使用这个工具使用实际的正则表达式。
(Please note that I am aware of the other possibilities for renaming files with regular expressions in a shell interpreter; this question aims at a specific version of the rename
tool.)
(请注意,我知道在shell解释器中使用正则表达式重命名文件的其他可能性;这个问题针对的是重命名工具的特定版本。
2 个解决方案
#1
4
Here is the manual page: http://linux.die.net/man/1/rename. It is pretty straightforward:
这里是手册页面:http://linux.die.net/man/1/rename。这是很简单的:
rename from to file...
重命名的文件……
rename will rename the specified files by replacing the first occurrence of from in their name by to.
rename将对指定的文件重命名为to,替换其名称中第一个出现的from。
I believe there are no regexes, it is just plain substring match.
我认为没有regexes,它只是普通的子字符串匹配。
#2
-1
The following command gives the expected result with your input file but using the perl
version:
以下命令给出输入文件的预期结果,但使用perl版本:
rename 's/foo_\D+(\d+)/foo_$1/' *.ext
You can test the command using -n
option to rename
您可以使用-n选项测试命令重命名
#1
4
Here is the manual page: http://linux.die.net/man/1/rename. It is pretty straightforward:
这里是手册页面:http://linux.die.net/man/1/rename。这是很简单的:
rename from to file...
重命名的文件……
rename will rename the specified files by replacing the first occurrence of from in their name by to.
rename将对指定的文件重命名为to,替换其名称中第一个出现的from。
I believe there are no regexes, it is just plain substring match.
我认为没有regexes,它只是普通的子字符串匹配。
#2
-1
The following command gives the expected result with your input file but using the perl
version:
以下命令给出输入文件的预期结果,但使用perl版本:
rename 's/foo_\D+(\d+)/foo_$1/' *.ext
You can test the command using -n
option to rename
您可以使用-n选项测试命令重命名