I'm trying to replace special characters with underscores (_) in the filenames of a directory and its subdirectories.
I have a folder named "folder1" that contains the following files:
-rw-r--r-- 1 macair staff 0 Apr 13 16:19 #ababa.txt
-rw-r--r-- 1 macair staff 0 Apr 13 12:51 @babba.txt
drwxr-xr-x 3 macair staff 96 Apr 24 15:55 Folder2
-rwxr-xr-x 1 macair staff 379 Apr 25 11:17 myScript
-rw-r--r-- 1 macair staff 0 Apr 13 16:19 test1.txt
and inside "folder2", I have the following file:
-rw-r--r-- 1 macair staff 0 Apr 24 15:55 #cdcda.txt
I tried running a script to change the filenames, but the changes are only being reflected in "folder1" and not in "folder2".
Here's the script I used:
#!/bin/bash
#find . -type f -exec grep -i "[^0-9a-z/.\/-\_]" {} \;
for FILE in $(find . -type f -exec basename {} \; | grep -i "[^0-9a-z\.\/_\-]")
do
echo $FILE
mv "$FILE" "${FILE/[!0-9a-zA-Z.-]/_}"
done
echo Done!!
but I received the following error:
mv: rename #cdcda.txt to _cdcda.txt: No such file or directory
As a beginner in Linux, I would appreciate any help or suggestions to improve the code above.
You did
-exec basename {}presumably to avoid replacing the directory separator/, but thereby you are losing directory information, so don't. When leaving the path intact, we just have to include the/in the class of normal characters: