Operating System - Linux
1753331 Members
5175 Online
108792 Solutions
New Discussion юеВ

scripting - running through a list

 
SOLVED
Go to solution
Peter Gillis
Super Advisor

scripting - running through a list

Hi.
HPux 11.11 v1.
This is going to be really basic,but for some reason I am just not able to get it.!
I have a file of names (first and second name per line).
I want to take each line and run a command on it...

file1 =
firstname1 lastname1
firstname2 lastname2

I want to do something like:

for i in `cat file1`
do
echo $i
done


and $i would echo back with
firstname1 lastname1

firstname2 lastname2


at the moment I am getting a list like:
firstname1
lastname1
firstname2
lastname2


I know this ridiculously easy.... please someone help
thanks Maria
8 REPLIES 8
Denver Osborn
Honored Contributor
Solution

Re: scripting - running through a list

while read fname lname
do
echo $fname lname \\n
done < file1

hope this helps,
-denver
Denver Osborn
Honored Contributor

Re: scripting - running through a list

sorry, I'm sure you'll catch this but I had a type-o. lname above should read $lname :)
A. Clay Stephenson
Acclaimed Contributor

Re: scripting - running through a list

cat file1 | while read NAME
do
echo "Name: ${NAME}"
done

If you want firstname and lastname as separate variables then:

cat file1 | while read FNAME LNAME
do
echo "First Name: ${FNAME} Last name: ${LNAME}"
done
If it ain't broke, I can fix that.
Peter Gillis
Super Advisor

Re: scripting - running through a list

Clay would you please send me a reply so I can assign your points correctly? I stuffed up again.
Thankyou both Denver and yourself, both methods worked for me.
Maria
A. Clay Stephenson
Acclaimed Contributor

Re: scripting - running through a list

Actually Denver's is the better construct as it does not need to spawn a separate process though I have learned over the years that for some strange reason the cat file | while read construct is more readily grasped/grokked/understood in examples.
If it ain't broke, I can fix that.
Peter Gillis
Super Advisor

Re: scripting - running through a list

I would say a huge thankyou to both of you. both examples were easy for me to understand and gave the required outcome. This medium is a great way to get exposure to different methods of achieving the same result. thanks again
Maria
Dennis Handly
Acclaimed Contributor

Re: scripting - running through a list

If you want something only a little harder to understand you can use xargs:
xargs -n2 echo < file1

-n2 says to put only 2 arguments on the echo command. If you wanted to have more text with the echo, you would have to execute a command.
Eric Raeburn
Trusted Contributor

Re: scripting - running through a list

This also works:

cat file | while read line ; do
echo $line
done



-Eric