1

How to remove leading whitespace from file and folder names? (I'm running OS X 10.6 Snow Leopard.)

As provided below by @Lri I was able to remove trailing whitespace using this:

#!/bin/bash

IFS=$'\n'
for d in {1..9}; do
    find ~/Desktop -name '* ' -depth $d | while read f; do
        mv "$f" "$(sed 's/ *$//' <<< "$f")"
    done
done

Now I'm trying to remove leading whitespace with this:

#!/bin/bash

IFS=$'\n'
for d in {1..9}; do
    find ~/Desktop -name '* ' -depth $d | while read f; do
        mv "$f" "$(sed 's/^ *//;s/ *$//' <<< "$f")"
    done
done

but it doesn't work.

What am I doing wrong?

3

I see two problems: first, you need the find command to look for names with spaces at the beginning instead of the end (-name ' *' instead of -name '* '). Second, f is going to be the full path to the file, not just its name; this means the spaces aren't at the beginning of the string, they're just after the last slash (e.g. "/Users/timoto/Desktop/ spacedfile"). This is a little more complicated to handle; the easiest way I thought of was to split the path using dirname and basename, and remove leading spaces from just the base part.

Also, there should be no need to run the command 9 times at different depths; just use the -depth option (without a number), and it'll return results in depth-first order (i.e. deepest files before their containing directories), which should prevent problems with directories getting renamed out from under processing the files in them.

IFS=$'\n'
find ~/Desktop -name ' *' -depth | while read f; do
    mv "$f" "$(dirname "$f")/$(basename "$f" | sed 's/^ *//;s/ *$//')"
done

EDIT: my basename/sed command was way more convoluted than it needs to be; simplified it...

2
  • Thanks for pointing out the -depth flag... I edited my answer to the original question as well.
    – Lri
    Mar 27 '12 at 12:07
  • This no longer seems to work as expected in macOS 10.11.6 Now removes leading and training space from folders, and leading space from filenames, but not trailing space from filenames.
    – timoto
    Jan 3 '19 at 5:46

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.