Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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 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?

share|improve this question
up vote 3 down vote accepted

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...

share|improve this answer
    
Thanks for pointing out the -depth flag... I edited my answer to the original question as well. – user495470 Mar 27 '12 at 12:07
    
Thank you both for helping find the solution. – timoto Apr 4 '12 at 21:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .