LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Need help with "read" command (https://www.linuxquestions.org/questions/linux-software-2/need-help-with-read-command-398768/)

WindowBreaker 01-02-2006 05:02 PM

Need help with "read" command
 
I have a file named /etc/values, with the following 3 lines:
Code:

Gonzales, Juan;California;June
Johnson, Paul;Wyoming;April
Smith, John;Wisconsin;February

I'm trying to figure out how to use the read command and need a little advice. I'd like run a script that prints out:

Code:

Name:  Gonzales, Juan
State:  California
Month:  June

Name: Johnson, Paul
State: Wyoming
Month: April

Name: Smith, John
State:  Wisconsin
Month:  February

Here is my script so far:
Code:

#!/bin/sh
## Set IFS variable to semicolon as delimiter
IFS=;
for i in `cat /etc/values`; do
 echo $i | read -a field
 echo -e "Name:\t${field[0]}"
 echo -e "State:\t${field[1]}"
 echo -e "Month:\t${field[2]}"
done

But it's not working.
The output I am getting is:
Code:

Name:
State:
Month

:

I have read "man bash" and have tried many variations, but still not working right. If you have any tips, or see what I am doing wrong, feel free to point it out.

NOTE: The actual file I'll be using will have hundreds of records, delimited by a semicolon. Within the fields, there will be spaces and commas.

btmiller 01-02-2006 06:39 PM

I'd use awk to do this, as it's perfect for this -- the following ought to work:

Code:

awk -F';' '{print "Name: ", $1, "\nState: ", $2, "\nMonth: ", $3, "\n\n"}' < /etc/values
I'm not totally sure how to do it in bash -- if I had to, I'd probably use read and then cut to split the line into its fields. IMO awk makes it much easier.


All times are GMT -5. The time now is 10:08 PM.