Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I remove trailing whitespace from file extensions and folders in snow leopard ?

Ideally I would be able to run a single command within a directory that would search and remove for all files and folders with trailing whitespace and their subfolders.

I couldn't seem to do this with automator.

It's a delicate operation I don't want to make mistakes with.

Help much appreciated.

share|improve this question
up vote 1 down vote accepted

find ~/Desktop -mindepth 1 -depth | while read f; do
    new="$(dirname "$f")/$(basename "$f" | sed 's/ *$//')"
    [[ "$f" != "$new" ]] && mv "$f" "$new"
  • Without IFS=$'\n', the f variables read by | while read f wouldn't have leading or trailing spaces
  • Changing sed 's/ *$//' to sed 's/^ *//;s/ *$// would remove spaces from the start as well
share|improve this answer
Thank you for the feedback. Now that you mention it I would certainly like to remove the leading whitespace too. I'm a bit confused how the script would look in that case. Do mean remove $'\n' and | while read to achieve this ? – timoto Mar 21 '12 at 15:51
's/^ *//;s/ *$//' would also remove spaces at the start. I meant that without IFS=$'\n' none of the f variables read by while read f would have trailing or leading spaces. – user495470 Mar 22 '12 at 7:03
If I enter the original on one line in Terminal I get: syntax error near unexpected token `do' and if run in a script i get command not found. – timoto Mar 22 '12 at 12:57
@timoto Was the single line version missing a semicolon after the IFS=$'\n' or something? The command not found error could be caused by trying to run the script like instead of ./ if it wasn't in your path. – user495470 Mar 22 '12 at 13:10
Yes I'm running the script as sudo ./ I also tried this on the cl IFS=$'\n'; for d in {1..9}; do find ~/test -name '* ' -depth $d | while read f; do mv "$f" "$(sed 's/ *$//' <<< "$f")" done done there was no error, but it just hung and did not return to the prompt. – timoto Mar 22 '12 at 14:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.