tags:

views:

43

answers:

2

Hello,

I need to rename all the files in a directory. Some examples of the source filenames are:

alpha--sometext.381928
comp--moretext.7294058

The resultant files would be renamed as:

alpha.sometext.381928
comp.moretext.7294058

The number of characters before and after the -- is not consistant.

The script needs to work on current installations of Ubuntu and FreeBSD. These are lean LAMP servers so only the necessary packages have been installed.

Thanks

+4  A: 

Via bash:

for file in *--*; do
    mv "${file}" "${file/--/.}"
done

The magic is in ${file/--/.} which is the value of ${file} except with each "--" changed to a "."

R Samuel Klatchko
Nice one. I was trying to write one but you beat me to it!
Josh
You should always quote any variable that contains filenames. `mv "${file}" "${file/--/.}"`
Dennis Williamson
@DennisWilliamson - I've updated my answer, but to be precise, you need to quote anything that may have whitespace in them.
R Samuel Klatchko
+4  A: 

As an alternative to pure shell, you can use rename, a standard utility that comes with Perl. It's more convenient for simple cases.

rename 's/--/./' *
ire_and_curses
That's really cool. Didn't know that.
tangens