Wednesday 25 March 2015

Script to replace special characters from files or directories recursively.



As a linux administrator, there may be a situation where you may want to replace special characters from a file or directory name.

You can easily rename such file or folder by command "mv <old file name> <new file name>". But what if you want to replace special characters of all files and folders present inside a directory. And also it should replace special characters recursively.

You can use following script to replace special characters. In following script, we have replaced special characters by "_" character.

1) Following script will check for special characters in all files and directories present under /mailstore.

2) If you want to replace special characters from another directory then modify script by providing path name of new directory instead of /mailstore.



-----------------------------------------------------------------------------------------------------------
#!/bin/bash

find /mailstore/ -depth -name "*[,&<>*?|\":'()$% ]*" |   # Find all files or folders containing 'special' characters under /mailstore.
while read FILEDIR                            # Read them line-by-line.
do

        DIR="${FILEDIR%/*}"                   # Get the folder its inside
        echo $DIR

        FILE="${FILEDIR/*\/}"                 # Get the plain name.
        echo $FILE

        NEWFILE="${FILE//[,&<>*?|\":\'()$% ]/_}" # Substitute _ for bad things.
        echo $NEWFILE

        mv "$DIR/$FILE" "$DIR/$NEWFILE"  # Rename it.

done

-----------------------------------------------------------------------------------------------------------

If anyone needs any modification or any other script, please mention a comment.

No comments:

Post a Comment