LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash, loops and spaces in filenames (https://www.linuxquestions.org/questions/programming-9/bash-loops-and-spaces-in-filenames-252338/)

shy 11-08-2004 04:08 AM

bash, loops and spaces in filenames
 
Hi.

I'm frequently using bash scripts like this:
Code:

for i in `ls *`; do
  #do something with $i
done

but I face some problems when files in current directory contain spaces in their names, because $i goes through words separated by spaces. For example,
Code:

$ touch "a b"; touch "c d";
$ for i in `ls *`; do echo $i; done       
a
b
c
d

What should I do to force the output be like this:
Code:

a b
c d

?

theYinYeti 11-08-2004 05:09 AM

I hope this helps:
Code:

#!/bin/bash

OLDIFS="$IFS"
IFS='
'
for fic in $(ls); do
        echo $fic
done
IFS="$OLDIFS"

Yves.

jschiwal 11-08-2004 05:15 AM

Use double quotes around the variable.

example:
for song in *.mp3; do mv " ${song}" "${song// /_}"; done
will replace spaces in the filenames with the underscore.

You will need to place the variable in double quotes anyway in
case the filename might contain characters like '()*!' which are
not whitespace but have a special meaning to the shell.

shy 11-08-2004 05:28 AM

Quote:

Originally posted by theYinYeti
I hope this helps:
Thanks, this helped :)

Quote:

Originally posted by jschiwal
for song in *.mp3; do mv " ${song}" "${song// /_}"; done

Well, quotes wasn't the case, you just don't use the output of ls, but use "*" directly. This is a bit simplier, thanks too.
But I'm wondering where can I learn more about renaming in the style of ${song// /_}?

theYinYeti 11-08-2004 07:18 AM

`man bash` is a great source of information. Tip, after typing man bash[enter], type this: "/\#\#" and [enter] and you'll be right at the interesting location.

Yves.

shy 11-08-2004 07:43 AM

Quote:

Originally posted by theYinYeti
`man bash` is a great source of information.
Thanks again, I was always to lazy to read `man bash` from start to end :(


All times are GMT -5. The time now is 09:25 AM.