Search code examples
macosbashsedosx-yosemite

How to remove trailing whitespace from file extensions with bash?


I first tried everything at How to remove trailing whitespace of all files recursively? and https://superuser.com/questions/402647/how-to-remove-trailing-whitespace-from-file-extensions-and-folders-snow , which did not work.

The file name for example is "image.jpg " and i want to convert it to "image.jpg".

Please help, It also should be recursive. example


Solution

  • find . -depth ... is the best answer, but unfortunately it's unavailable to you (unless you install homebrew)

    One difficulty of the for solution is that it does not descend into the directory hierarchy depth-first. So you're in danger of renaming a directory first, and then failing to rename any of the files under it.

    To ensure that you're renaming files before any parent directory is to find the files and then reverse sort:

    shopt -s globstar nullglob extglob
    printf "%s\n" **/*[[:space:]] | sort -r | while IFS= read -r filename; do
        newname=${filename/%+([[:space:]])}
        mv "$filename" "$newname"
    done