Question

I am looking for a script to rename files and directories that have special characters in them. My files:

?rip?ev <- Directory
 - Juhendid ?rip?evaks.doc <- Document
 - ?rip?ev 2 <- Subdirectory
 -- t?ts?.xml <- Subdirectory file

They need to be like this:

ripev <- Directory
 - Juhendid ripevaks.doc <- Document
 - ripev 2 <- Subdirectory
 -- tts.xml <- Subdirectory file

I need to change the files and the folders so that the filetype stays the same as it is for example .doc and .xml wont be lost. Last time I did it with rename it lost every filetype and the files were moved to mother directory in this case ?rip?ev directory and subdirectories were empty. Everything was located under the mother directory /home/samba/.

So in this case I need just to rename the question mark in the file name and directory name, but not to move it anywhere else or lose any other character or the filetype. I have been looking around google for a answer but haven't found one. I know it can be done with find and rename, but haven't been able to over come the complexity of the script. Can anyone help me please?

Was it helpful?

Solution

You can just do something like this

find -name '*\?*' -exec bash -c 'echo mv -iv "$0" "${0//\?/}"' {}  \;

Note the before the so you can see what it does before actually changing anything. Otherwise above:

  • searches for ? in the name (? is equivalent to a single char version of * so needs to be escaped)
  • executes a bash command passing the {} as the first argument (since there is no script name it's $0 instead of $1)
  • ${0//\?/} performs parameter expansion in replacing all occurrences of ? with nothing.

Note also that file types do not depend on the name in linux, but this should not change any file extension unless they contain ?.

Also this will rename symlinks as well if they contain ? (not clear whether or not that was expected from question).

OTHER TIPS

I usually do this kind of thing in Perl:

#!/usr/bin/perl

sub procdir {
  chdir @_[0];
  for (<*>) {
    my $oldname = $_;
    rename($oldname, $_) if s/\?//g;
    procdir($_) if -d;
 }
  chdir "..";
}

procdir("top_directory");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top