I have a script that searches for space characters '
', exclamation marks '!
' and dollar signs '$
' in filenames and replaces each with an underscore '_
'. However, it does not handle file names with exclamation marks in them, at all. Files to be renamed are searched for in the current folder and all sub-folders up to a certain depth (not very relevant here). Folder names should also be changed in the same way, that's why the depth is staggered.
This is the desired renaming scheme:
This is cool!.txt --> This_is_cool_.txt
Thank$.log --> Thank_.log
Foo 1/Bar 2/a.txt --> Foo_1/Bar_2/a.txt
Here is the script:
#!/bin/tcsh -f
foreach n ( 1 2 3 4 5 6 7 8 )
find . -mindepth $n -maxdepth $n -name '*[ $\!]*' | fgrep -v \" | \
awk '{printf "mv -i -- \"%s\" \"%s\"\n", gensub("!","\\\\\!","g",$0), gensub(" ","_","g",gensub("\\$","\\\\$","g",gensub("!","\\\\\!","g",$0)))}' | tcsh -cf
end
I have varied the number of backslashes '\
' before both exclamation marks but to no effect. Error messages may look like this (even number of backslashes):
awk: cmd. line:1: warning: escape sequence `\!' treated as plain `!'
or the shell script (apparently) opens an interactive shell?! Sometimes nothing happens at all (I suppose when there are too many backslashes in the first argument to mv
and the file is not found).
PS: As you can see I excluded files with a double quote '"
' in them because I also could not get those to work, either. If you could suggest how to handle those as well, all the better!
awk: cmd. line:1: warning: escape sequence '\!' treated as plain '!'
. I did try| bash
but that did not work either somehow. If you have an answer with a different shell I am very open to it, though!-mindepth
and-maxdepth
? Is it only to avoid errors caused by renaming directories before possibly renaming files in them? Or do you want to exclude depth >8?tcsh
in interactive mode. Perhaps I need to switch for scripts.