I want to recursively rename files and directories from the current directory. The characters < > : " \ | ? * / should be removed. Also remove the spaces at the start and end of a filename. This is what I have so far, it's giving me trouble with the / of the subdirectories:

find . -depth -exec rename -n 's![:<>/"\\|?*]!!g; s/ *$//g' {} \;

Edit: The trouble that it gives me with / is that it's replacing the forward slash separating directories and introducing the subdirectory into the name of the file. So according to this answer it should be something like this:

LC_ALL=C find . -depth -execdir rename -n 's![:<>/"\\|?*]!!g; s/( *$)//g' {} +

Now it gives me a problem with filenames with newlines, it thinks each line is a different file and it's trying to rename files that don't exist. Also the rename should only execute for files that present problems in the filenames, so use the -name flag for find. It also needs to remove the spaces at the start. I need some explanation on each part of the command used in the answer. I don't even remember why I have copied the LC_ALL=C.

Maybe this fixes the problems, I still have to try it:

LC_ALL=C find . -depth -exec rename -n 's![:<>/"\\|?*]!!g; s/\n/ /g; s/ *$//g; s/^ *//g;' {} \;

The context is that I had to do chkdsk /f e: to fix a hard drive that couldn't mount on Linux Mint. chkdsk fixed the problem but it moved and renamed every file with special characters. So now I had to move and rename again those files as they were before but without special characters. I want to have a way to avoid all that, by running a command to fix the names from time to time so I don't run into the same problem again. That's why I asked this question.

  • What is the trouble that it gives you: edit question to tell us. – ctrl-alt-delor Mar 11 at 19:25
  • What OS did these files come from? – ctrl-alt-delor Mar 11 at 19:26
  • The files came mostly from the internet. I don't know which OS. But I do use the hard drive in linux mostly. – ajr-dev Mar 11 at 19:46
  • How would you define "closest-looking character"? – AdminBee Mar 12 at 13:50
  • I was thinking about unicode characters but that will introduce another problem. Which would be characters not displaying properly. So I'll change that in the question. – ajr-dev Mar 12 at 14:13

Browse other questions tagged or ask your own question.