Operating System - Linux
1753733 Members
4702 Online
108799 Solutions
New Discussion юеВ

Re: using "for' in script

 
SOLVED
Go to solution
sebastien_7
Occasional Advisor

using "for' in script

Hello,

I have a file which contains a list of backup names, some names have spaces some don't, when using the following it appears that the names with space are treated as two.

for i in `cat $file1 | awk -F"\t" '{print $1}'`;do
echo $i
done

file1 contains things like:
backup1 offline
backup2_online
etc...

I am sure there is a way around this but cannot find it.

Please help
Sebastien
7 REPLIES 7
john korterman
Honored Contributor

Re: using "for' in script

Hi,
try with qoutes
echo "$i"

regards,
John K.
it would be nice if you always got a second chance
Slawomir Gora
Honored Contributor
Solution

Re: using "for' in script

Hi,

try "while" insted of "for":

cat $file1 | while read
do
echo ${REPLY}
done
sebastien_7
Occasional Advisor

Re: using "for' in script

thanks guys,
That was pretty fast, Slawomir's suggestion worked just fine using this:
cat $file1|awk -F"\t" '{print $1}'|while read
do
echo ${REPLY}
done

thanks again
sebastien
Tim D Fulford
Honored Contributor

Re: using "for' in script

Hi

The problem is you are in effect writing

for i in backup1 offline backup2_online
do
...
done

So the for loop cannot differentiate (even with quotes). You need to join them together. Perl would probably be the tool of choice, but as you've chosed awk I'll do it like so...Try

for i in $(cat file | awk -F"\t" '{print $1}' | sed -e "s/\ /:/g")
do
j=$(echo $i | sed "s/:/\ /g")
etc...
done

Tim
-
Lisa Sorbo
Frequent Advisor

Re: using "for' in script

Hope I can tag on this thread. I have the same issue with spaces in file names - the listed solutions work for the echo stmt but I need to work with these files using a cp or mv or rm command - and I find that the same variable that is fine in the echo statement goes to the cp stmt in pieces again.

For example, if I get the file name into variable j, the stmt #cp /here/$j /there/$j will parse out the filename up to the first space.

any suggestions ?

Lisa
A. Clay Stephenson
Acclaimed Contributor

Re: using "for' in script

cp /here/$j /there/$j

cp "/here/${j}" "/there/${j}"

Disciplined shell programmers get into the habit of encloses all variables with {}'s and quoting as well because whitespace has always been legal (if dumb) in UNIX pathnames.
If it ain't broke, I can fix that.
Muthukumar_5
Honored Contributor

Re: using "for' in script

For loop will handle based on delimiters space or tab or new line also. You have to use while loop to handle "\n" as Record seperator. It is handled by IFS variable.

while read line;
do
echo $line
done <

It is more efficient than cat file | while.

===

lisa,

You can use methods as,

touch "hi bye"
here hi bye is a single file name.
var="hi bye"

You can move as,

# mv "$var" hi

or

# mv ${var} hi

hth.
Easy to suggest when don't know about the problem!