string operation

Hi all,

Here is my situation.

I have a text file TXT_FILE like this:
john 123456
jack 94589
kelvin 94595
mary 88585

I want to read the first word in each line ( the name ) and assign to a string variable ( EX_LIST ) in my script so that I can use later as this command

for i in $EX_LIST ; do ...

This is my complete script:

 #!/bin/sh

EX_LIST=' '
TXT_FILE=./my_file.txt

get_first()
{
        cat $TXT_FILE |while read line
        do
                first_word=`echo $line | awk '{print $1}'`
                echo This is first word: $first_word
                tmp_list=$EX_LIST
                echo This is temp list: $tmp_list
                EX_LIST=$tmp_list" "$first_word
                echo update new list: $EX_LIST
                echo ======***======
        done
        echo $EX_LIST
}

get_first

echo Printing out the result:
for nn in $EX_LIST ; do
        echo item: $nn
done
echo done!

 

And this is the result of my script:

This is first word: john
This is temp list:
update new list: john
======***======
This is first word: jack
This is temp list: john
update new list: john jack
======***======
This is first word: kelvin
This is temp list: john jack
update new list: john jack kelvin
======***======
This is first word: mary
This is temp list: john jack kelvin
update new list: john jack kelvin mary
======***======

Printing out the result:
done!

The problem as you can see is it does not echo anything of my for command. (Printing out the result:)
can anyone help to correct it ?
Thank you!

try this

while read line
do
        first_word=`echo $line | awk '{print $1}'`
        echo This is first word: $first_word
        tmp_list=$EX_LIST
        echo This is temp list: $tmp_list
        EX_LIST=$tmp_list" "$first_word
        echo update new list: $EX_LIST
        echo ======***======
done < $TXT_FILE

You can also do :

EX_LIST=`awk '{print $1}' $TEXT_FILE`

Jean-Pierre.

@ anbu23: It does not work, but thank you anyway for your kind of help.
@ Jean-Pierre: Just one line and great again! (you helped me twice). Thank you so much! :slight_smile:

$EX_LIST is not global and only filled within the get_first function.
If you change the last part to:
EX_LIST2=`get_first`

echo Printing out the result:
for nn in $EX_LIST2 ; do
echo item: $nn
done
echo done!

Mels

Oh, i see.
Thank you mels!

PS: But i have declare EX_LIST=' ' right at the beginning of the script. It should be global, right ?
Please explain me!

Its shell and not c or other programming language.
If a shell is running a function in an other shell, everything defiend in the last shell is not available in the first shell.

Mels