skip to Main Content

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.

4

Answers


  1. Try this:

    find /home/account -depth -name "* " | sed "s// ///g"
    
    Login or Signup to reply.
  2. -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' _ {} +
    
    Login or Signup to reply.
  3. You can use bash substitution to extract the file name, and eliminate leading spaces.

    Minor note: the pattern -name "* " looks for file with a trailing space(s). If you are looking for a filter for leading space(s) use -name " *", or for any space than -name "* * ". Sample code uses leading space pattern. You can adjust pattern and sed as needed.

    find /home/account -depth -name " *" | while read fn ; do
       d=${fn%/*}
       b=$(echo "${fn##*/}" | sed -e 's/^ *//')
       mv "$fn" "$d/$b"
    done
    
    
    Login or Signup to reply.
  4. use rename

    • -name “* “ : matches filenames having trailing spaces in their names
    • rename ‘s/ //gi’ : replace space with nothing

    –>

    find /home/account -depth -name "* " | rename 's/ //gi'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search