Search code examples
bashfindrenamefile-renamebatch-rename

Remove special chars from filenames


I need to remove all special chars from filenames.

Something like find . -mindepth 1 -exec rename 's/[^a-zA-Z0-9_-]//g' {} \; but when rename command renames dir find prints error about no such file or directory (old dir name).

And I need to allow dot.


Solution

  • Based on the answer of @matias-barrios, I wrote my own solution:

    #!/bin/bash
    fileList=$(find . -mindepth 1)
    echo "$fileList" | awk '{print length, $0}' | sort -rn | cut -d" " -f2- | 
    while read path; do 
      dirName=$(echo "$path" | rev | cut -d'/' -f2- | rev)
      fileName=$(echo "$path" | rev | cut -d'/' -f1 | rev)
      newFileName="$dirName/$(echo "$fileName" | tr -C -d 'a-zA-Z0-9-_.')"
      if [ "$path" = "$newFileName" ]; then continue; fi;
      echo "From: $path"
      echo "To: $newFileName"
      mv "$path" "$newFileName"
    done