LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   read a line from text file and extracting the details needed (http://www.linuxquestions.org/questions/linux-newbie-8/read-a-line-from-text-file-and-extracting-the-details-needed-647532/)

pdklinux79 06-06-2008 07:56 PM

read a line from text file and extracting the details needed
 
Hi ,
I need to read line from a txt file.
then if the line has ID, then get the value of ID and save it in a variable/array
else if the line has State , then get the value of state and store it in a variable/array

how do i go about it?

Im able to read the lines. but when i grep each line to find if there id word ID or State, im failing and im unable to assign the value to a variable..

Please anyone help me...
im a newbie...

i92guboj 06-06-2008 08:03 PM

Code:

grep ID filename.ext | while read line
do
  field_1=$(echo "$line" | awk '{print $1}')
  field_2=$(echo "$line" | awk '{print $2}')
  field_3=$(echo "$line" | awk '{print $3}')
  field_4=$(echo "$line" | awk '{print $4}')
# <---do whatever--->
done


pdklinux79 06-06-2008 08:19 PM

The result for field_1:
ID
:
0

now how do i use ID=0 for running a text? i need to extract the value for ID from field_1.. how do i do it?

Thank you

pdklinux79 06-06-2008 08:23 PM

cant i just store field_1 = 0 , field_2=1 instead of field_1 = ID : 1 ??how do i accomplish that?

Tinkster 06-06-2008 08:51 PM

Can you paste some sample input and the desired results?



Cheers,
Tink

rlhartmann 06-06-2008 10:35 PM

Quote:

Originally Posted by pdklinux79 (Post 3177155)
cant i just store field_1 = 0 , field_2=1 instead of field_1 = ID : 1 ??how do i accomplish that?


If ID only appears once in the file, you can use this

[QUOTE]
VALUEOFID=$(grep "ID=" datafile | read ID FIELD2 FIELD3 | awk -F= '{print $2}')[/QOUTE]

If it appears multple times, just feed the grep into
a while read ID field2 field3 line and

grep "ID=" datafile | while read ID FIELD2 FIELD3
do
VALUEOFID=$(echo "$ID" | awk -F= '{print $2}')


### What your going to do with ID

done

i92guboj 06-06-2008 10:41 PM

As Tinkster already suggested, please, post:

1.- a few lines, with sample contents of the file you are going to parse
2.- a very detailed example of a line, the value of fields that you expect, the value of ID (which I don't know what's supposed to be) and the expected results. Be as clear as you can, please.


All times are GMT -5. The time now is 10:47 AM.