How to rename files and replace characters?

I have a group of files that have : (colon) within the name. I need to replace the : with - (dash).

Is there an easy way to do this in a script?

Sample FileName: 2013-10-11:11:52:08_055456663_045585_.txt


Solution 1:

A simple 1-liner should do (assumes Posix sh-compatible shell):

for f in *:*; do mv -v "$f" $(echo "$f" | tr ':' '-'); done

Explanation:

  • for ... in ...; do ...; done is a loop

  • *:* matches all files and directories in the the current directory which have : in their name

  • f is assigned in turn to each such file name in the loop

  • mv renames its first argument to the second one; -v (verbose) asks it to print what it does; this option is GNU-utils specific, so it is available on Linux but not Solaris

  • $(...) executes the code in a sub-shell and substitutes the output

  • echo prints its argument to the standard output

  • tr reads standard output and translates the characters according to the supplied map

If you are using bash, you can avoid spawning an extra shell ($()) with sub-processes (tr) by replacing $(...) with ${f//:/-}.

Solution 2:

As stated in another post by me the rename tool could do the trick for you. You just need to type rename s/:/-/ <files to rename> This replaces every colon with a dash in all files you name at the end, i. e. 2013-10-*

Here's the link to my other Post

Solution 3:

I'm sure a UNIX pro could do this with bash, but here's my quick and dirty version with ruby.

path_to_files = "/home/username/wrongnames/"
filenames = `ls #{path_to_files}`.split
filenames.each do |fn|
  `mv #{path_to_files + fn} #{path_to_files + fn.gsub(/:/, "-")}`
end

set path_to_files to the path to your misnamed files. save the above code in a file called rename.rb then:

username@machinename$ ruby rename.rb