Marcus Brunström
Marcus Brunström

Reputation: 65

Remove space before filename and folders recursively

I'm currently moving content from an old xServe to a Synology NAS and the client decided 10 years ago to add one or more spaces before filenames and folders to make them appear higher up in the tree. When moving everything to the Synology NAS we're getting a lot of errors because of this.

The ideal solution for me would be to have a script that removes only the space(s) before the name and keeps the rest.

I found another similar thread here but that removes any space regardless of where it is found in the name. The script from the other thread is

find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;

Does anyone have an idea?

Thank you!

Upvotes: 1

Views: 1779

Answers (3)

Moritz Sauter
Moritz Sauter

Reputation: 167

Something like that should do the trick:

for i in "/path/to/directory with spaces/"* ; do
    dirname="$(dirname "$i")" # replace with the hardcoded path if you want
    newname="$(echo "$i" | sed "s|$dirname/ \+|$dirname/|")"
    # redirect to /dev/null if there are collisions or files without leading spaces
    mv "$i" "$newname" 2>/dev/null
done

You could write it as oneliner, but then it looks somehow messy with ". I suggest wrapping into a script with replacing the directory with $1.

Upvotes: 0

Marcus Brunström
Marcus Brunström

Reputation: 65

Thank you for helping out. With the help of Jean-Baptiste Yunès I managed to get this command that works perfectly. Thanks for all your help!

find /your-folder/ -depth -name "* *" -execdir rename 's/^ *//' "{}" \;

Upvotes: 1

I0_ol
I0_ol

Reputation: 1109

This should do what you are asking.

for oldname in /path/to/directory/* 
do
    newname="$(echo $oldname | sed 's/^ //')"
    #echo 'mv' "${oldname}" "${newname/ /}" ## Uncomment this line to test 
    mv "${oldname}" "${newname/ /}"
done

Upvotes: 1

Related Questions