linuxbashremoving-whitespace

Detect & remove leading space in file or folder name


I need to detect and remove lot of leading spaces on my folders & files.

i try some code like :

find /home/account -depth -name " *" -exec sh -c 'f="{}"; mv -v "$f" "...."' \;

but i couldn't find any code to remove leading space from filename or folder.

i need to :

mv "/home/account/folder/ folder 1"  "/home/account/folder/folder 1"

(because i use find, and make it detect leading spaces on sub folders)

how do i remove those leading space with code that i mentioned above ? any advice would help. btw, i'm using centos 7.


Solution

  • -name "* " matches filenames having trailing spaces in their names. I fixed that below, and used -execdir to make it easier to remove leading space using parameter expansions.

    find /home/account -depth -name ' *' -execdir sh -c '
    for f; do
        mv -v "$f" "${f#./[[:space:]]}"
    done' _ {} +
    

    For a dry-run precede mv with echo.


    If there might be multiple leading spaces then the convenient way is to use an extglob (which is a bash extension) in the parameter expansion:

    find /home/account -depth -name ' *' -execdir bash -c '
    shopt -s extglob
    for f; do
        mv -v "$f" "${f#./+([[:space:]])}"
    done' _ {} +