Search code examples
bashfish

Bash script to remove leading white spaces from files names


So I have a bunch of files like:

 Aaron Lewis - Country Boy.cdg
 Aaron Lewis - Country Boy.mp3
 Adele - Rolling In The Deep.cdg
 Adele - Rolling In The Deep.mp3
 Adele - Set Fire To The Rain.cdg
 Adele - Set Fire To The Rain.mp3
 Band Perry - Better Dig Two.cdg
 Band Perry - Better Dig Two.mp3
 Band Perry - Pioneer.cdg
 Band Perry - Pioneer.mp3

and I need to have the leading whitespace removed in bash or fish script.


Solution

  • To remove the leading white space char in the file names you provided you can use:

     IFS=$'\n'
     for f in $(find . -type f -name ' *')
     do 
         mv $f ${f/\.\/ /\.\/}
     done
    

    This:

    • changes the IFS to only be newline characters; this way it does not choke on the whitespaces in the file names.
    • finds all files starting with a whitespace in the current directory.
    • moves each file to a file name without the leading whitespace, using bash substring substitution.