0

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.

1
#!/bin/bash

IFS=$'\n'
find ~/Desktop -mindepth 1 -depth | while read f; do
    new="$(dirname "$f")/$(basename "$f" | sed 's/ *$//')"
    [[ "$f" != "$new" ]] && mv "$f" "$new"
done
  • 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
14
  • 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. – Lri 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 script.sh instead of ./script.sh if it wasn't in your path. – Lri Mar 22 '12 at 13:10
  • Yes I'm running the script as sudo ./script.sh 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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