Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename all '.' to '_' in a filename except for the extension

I am trying to create a script that replaces all the "." occurences in a filename with "_". For example when I try to replace all the " " symbols I use this:

rename 'y/ /_/' '{}' file
# test 1.2.jpg -> test_1.2.jpg

Which works fine, but when I try to do it with the "." symbol the extension also changes:

rename 'y/./_/' '{}' file
# test 1.2.jpg -> test 1_2_jpg

How can I rename the file without changing the extension (when there is one)?

like image 265
tversteeg Avatar asked Feb 17 '14 09:02

tversteeg


1 Answers

You can use a lookahead to replace all dots before the very last dot:

rename 's/\.(?=[^.]*\.)/_/g' '{}'

OR using negative lookahead:

rename 's/\.(?![^.]*$)/_/g' '{}'
like image 76
anubhava Avatar answered Oct 11 '22 23:10

anubhava