3

I have around 300 files named

some_name_123456789.zip
another-name2_987654321.zip
something(1)_123454321.zip
[2]something_987656789.zip

I need to rename them all to

ds_123456789.zip
ds_987654321.zip
ds_123454321.zip
ds_987656789.zip

How can i do this?

An Dorfer
  • 1,178
  • 2
  • 8
  • 14
Xseba360
  • 33
  • 1
  • 1
  • 3

2 Answers2

10

You can do this with the rename command line utility. To do what you want you need a simple regular expression:

rename "s/.+_/ds/g" files

.+ represents everything up to (in this context) the last underscore (_) character (so this works with multiple underscores, as mentioned in your first example). This requires that there be at least one character before the underscore; if you might have file names like _20131012.zip, use .* instead. So this three-character string (.+_ or .*_) will match everything up to and including the last underscore in the filename. s/old/new/ means substitute the new string (ds) for the old string. The g means global and might not be necessary in this case.

noggerl
  • 1,349
  • 9
  • 10
  • To be sure that the regexp matches from the beginning I would rather put `^` to the beginning. Also OP wanted to retain the underscore. The `g` option at the end is not really needed here - it would match multiple instances in the file name if possible. So I think this command would perform better: `rename "s/^.+_/ds_/" files` – pabouk - Ukraine stay strong Oct 12 '13 at 21:40
  • adding the `g` is just a standard habit from me and i agree that it's not needed in this case. – noggerl Oct 12 '13 at 21:45
  • Does this work for a list of folders too or what do you add to make it? – Timothy Sep 29 '14 at 15:23
  • Maybe i would use the find utilty the exec option, but this depends on the names of the files you are working on. To rename the zip files mentioned above you can use `find . -name "*.zip*" -exec rename "s/.+_/ds/g" {} \;` where "{} \;" is the variable for the filename find returns. – noggerl Oct 09 '14 at 09:13
1

or, using the cross-platform renamer:

$ renamer --regex --find '.+_' --replace 'ds' *
Lloyd
  • 121
  • 3