Pregunta

I am basically trying to replace all special characters in directory names and files names with a period. I am attempting to use tr, but I am very new and I do not want to mess up all of my music naming and picture naming. I am making the switch from windows to linux and trying to get everything in a nice formatted pattern. I have used tr semi successfully but I would like some pro help from you guys! Thanks in advance! I have looked at the tr man pages but I am just worried about really messing up 12 years of pictures and music file names! The two man characters I am trying to replace are " - " but the naming scheme I've used in windows has been by hand over the years and it varies, so I was hoping to go through everything and replace all cases of "-" or " - " manly but any fat fingering I have done over the years and put in something besides that patter would be great. I am thinking something like:

tr -cd [:alnum:] '.'

would this work?

My main goal is to turn something like

01 - Name Of Song (or any variation of special/punctuation characters)

into

01.Name.Of.Song

¿Fue útil?

Solución

You don't want to use the d option since it just deletes the matched characters. And you may want to use the s (squeeze) option. Try this:

tr -cs '[:alnum:]' '.'

You can test it like this:

echo '01 - Name Of Song' | tr -cs '[:alnum:]' '.'

(Ignore the extra period at the end of the output. That's just the newline character and won't appear in filenames ... generally.)

But this is probably not of much use in your task. If you want to do a mass rename, you might use a little perl program like this:

#!/usr/bin/perl

$START_DIRECTORY = "Music";
$RENAME_DIRECTORIES = 1;   # boolean (0 or 1)

sub procdir {
  chdir $_[0];
  my @files = <*>;
  for my $file (@files) {
    procdir($file) if (-d $file);
    next if !$RENAME_DIRECTORIES;
    my $oldname = $file;
    if ($file =~ s/[^[:alnum:].]+/\./g) {
      print "$oldname => $file\n";
#      rename $oldname, $file; # may not rename directories(?)
    }
  }
  chdir "..";
}

procdir($START_DIRECTORY);

Run it with the rename command commented out (as above) to test it. Uncomment the rename command to actually rename the files. Caveat emptor. There be dragons. Etc.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top