Operating System - HP-UX
1826312 Members
4357 Online
109692 Solutions
New Discussion

Simple scripting question

 
SOLVED
Go to solution
Tim Medford
Valued Contributor

Simple scripting question

I'm sure this is simple, but I've been hung up for a couple hours on it.

I have a "for" loop which cats a file. The file contains 2 columns of data separated by a space. I want each line to come into the loop as 1 argument instead of two. No matter how I've tried to quote things it keeps treating each word in the document as 1 pass through the loop.

for i in `cat /tmp/rfile`
do
echo $i
done

assuming /tmp/rfile contains:
abc 123
def 456
etc...

The output looks like
abc
123
def
456

I want it to look like
abc 123
def 456

I want the value of $i to be "abc 123" first time, and "def 456" second time.

Thanks in advance!
Tim
8 REPLIES 8
Patrick Wallek
Honored Contributor
Solution

Re: Simple scripting question

How about this:

while read i
do
echo $i
done < test
harry d brown jr
Honored Contributor

Re: Simple scripting question


Add this to your cat:

cat /tmp/rfile|sed "s/ //g"

or if they are possibly tabs and/or spaces:

cat /tmp/rfile|sed "s/[[:space:]]//g"


live free or die
harry
Live Free or Die
A. Clay Stephenson
Acclaimed Contributor

Re: Simple scripting question

Let's change the loop a bit:

#!/usr/bin/sh

cat /tmp/rfile | while read i
do
echo "${i}"
done
If it ain't broke, I can fix that.
Ian Kidd_1
Trusted Contributor

Re: Simple scripting question

I tested this and it seems to work fine:

exec 3< /tmp/rfile
i=`line <& 3`
while test "$?" -eq 0
do
echo $i
i=`line <& 3`
done

those are back-tiks rather than single quotes.

If at first you don't succeed, go to the ITRC
Patrick Wallek
Honored Contributor

Re: Simple scripting question

In my above post the 'test' is the filename you are redirecting back into the little script.

My file looked like this:

# cat test
abc 123
def 456
ghi 789
James R. Ferguson
Acclaimed Contributor

Re: Simple scripting question

Hi Tim:

This will yield what you seek:

while read F1 F2
do
echo $F1 $F2
done < /tmp/rfile

Regards!

...JRF...
Hai Nguyen_1
Honored Contributor

Re: Simple scripting question

Tim,

Try this small program:

while read LINE
do
echo $LINE
done
Hai
Rodney Hills
Honored Contributor

Re: Simple scripting question

To expand on the above script,

IFS=""
while read LINE
do
echo $LINE
done
Setting IFS to null will prevent "read" from breaking up the input line into "words".

HTH

-- Rod Hills
There be dragons...