简体   繁体   中英

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

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

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

OR using negative lookahead:

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

rename -n 's/ \\.(?=.*\\.)//g' * : -n no action. To actually make changes remove -n.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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