5

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.

2
  • Do you mean you're renaming the files to not have the white space in front, or are these file names stored in a text file and you need to process them? Commented May 29, 2013 at 23:11
  • I want to rename files to not have the white space in front. Commented May 29, 2013 at 23:31

4 Answers 4

5

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.
Sign up to request clarification or add additional context in comments.

2 Comments

That did it! I always forget about IFS. That was what was killing my own script. Thanks
Doesn't work, returns "mv: '...' and '...' are the same file". I suspect this only works in the current directory, not recursively.
0
for x in \ * ; do mv "$x" `echo "$x" | sed "s/^ +//"` done 

This is quick and dirty.

2 Comments

no go. I get this usage: mv [-f | -i | -n] [-v] source target mv [-f | -i | -n] [-v] source ... directory
Interesting. I ran this in a bash shell and it worked for me. I just did it again to be sure: I copy and pasted those lines exactly to my shell terminal and it renamed my files that started with space to files that don't start with space. I'm running Fedora 17 Linux. What flavor of Unix are you running?
0

cat <file> | sed -e 's/^[ ]*//'

should do the trick. Capture stdout and write to a file.

1 Comment

Im looking to remove the leading spaces in file names. Not file content. Good try though.
0

You don't need sed for this. Just use bash string function:

for file in /path/to/files/*; do mv "$file" "${file# *}"; done 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.