LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash Scripting Question (https://www.linuxquestions.org/questions/programming-9/bash-scripting-question-29948/)

RefriedBean 09-09-2002 03:49 AM

Bash Scripting Question
 
Hi!
I'm working on a simple script that passes a filename stored in a file (each filename is stored on a seperate line), as an argument to a program.

It uses a for loop.

Code:


for i in $( cat ~/.list ); do
      program $i
done

I have a few files that contain spaces, like;

aaaaa\ bbb.jpg

The problem is, that 'for' takes that as two names, thus the program won't work on files with spaces.

Now my question;
How can I make it see a filename with spaces in as one name?

Thanks!
RefriedBean

Mik 09-09-2002 06:18 AM

If you have quotes around the filenames with spaces in the .list file then you can easily use xargs to get it to run the command with each filename seperately. Something like:

cat ~/.list | xargs -n 1 programname

You can get ls to put quotes around each filename so you could do something like this.

ls --quoting-style=c *.jpg | xargs -n1 programname

That would run the program for each .jpg file in the current directory even if it had spaces in the name.

no2nt 09-09-2002 07:21 AM

this should do the job

Code:

for i in "$( cat ~/.list )";
do
    program "$i"
done


Mik 09-09-2002 07:44 AM

no2nt your example would work for one file with spaces in it. But it won't call the program one time for each filename in the list file. It just sends the complete list of files as one argument and only calls the program once.

no2nt 09-09-2002 10:19 AM

oh, i'm extremely sorry. I left something out!

Code:

IFS=$'\n'  # we need to handle tabs and spaces properly
for i in $( cat ~/.list );
do
    program "$i"
done
unset IFS  # return the inter-field separator to normal

thanks for showing me my error of ommision :-)

Mik 09-10-2002 02:14 AM

That IFS parameter is rather handy. I gotta remember that one.

RefriedBean 09-11-2002 09:06 AM

Thank you for all for your replies!

RefriedBean


All times are GMT -5. The time now is 11:09 PM.