Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex with `rename` version from `util-linux`

Tags:

regex

linux

bash

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.

There are two versions of rename :

  • The “Perl” version, with syntax rename 's/^fgh/jkl/' fgh*
  • The util-linux version, with syntax rename fgh jkl fgh*

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.

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.)

like image 446
Arcturus B Avatar asked Jul 14 '15 13:07

Arcturus B


1 Answers

Here is the manual page: http://linux.die.net/man/1/rename. It is pretty straightforward:

rename from to file...

rename will rename the specified files by replacing the first occurrence of from in their name by to.

I believe there are no regexes, it is just plain substring match.

like image 104
buff Avatar answered Sep 22 '22 16:09

buff