Hi all
I have a problem where i have a large list ( up to 1000 of items) and need to have 2 items pulled from it into variables in a bash script
my list is like the following and I could have it as an array or possibly an external text file maintained separately. Every line is different and will be up to 500 lines, and is rather static content, so could easily be a CSV or similar.
15, Hills District,HIL
53,Kings Langley, KIN
76,Winston Hills,WIN
My script has the first term, (the number) as a variable and needs to use this to fined the corresponding entries on that line, and write them to 2 new variables.
Eg
if $Cnum = 56 then it will return
$cname = Kings Langley
$csname = KIN
I could build and array at run time for 1 variable, but how could I do it and return the 2 varaibles?
while IFS="," read Cnum came csname;do
echo -e "Cnum: $Cnum\ncname: $cname\ncsname: $csname"
done<file.txt
Note also that echo -e is not portable to systems conforming to the POSIX standards nor to the Single UNIX Specifications.
For maximum portability, it could be written as:
while IFS="," read Cnum came csname
do printf "Cnum: %s\ncname: %s\ncsname: %s\n" "$Cnum" "$cname" "$csname"
done<file.txt
(Note that changing ;do at the end of the while line to the start of the next line is just my preferred shell script coding style. The shell is happy with both forms.)
EDIT: Or, if you insist on arrays: either use two arrays with a common index, or concatenate the two values into one with a unique separator (which then, on retrieval, you would need to separate again).
Thank you Rudi,
this was exactly what i need to achieve and probably the easiest way to do it.
A Single line of code to read an external file and write the data to 2 variables.
Hi kcpoole,
I'm very glad that RudiC's code worked for you. Note that with the request you made in the 1st message in this thread (where you set CNum=56 and said you wanted to get:
$cname = Kings Langley
$csname = KIN
even though no line in your input file had a 1st column containing the value 56), RudiC's code would print:
56,,
rather than what you asked for.
I guess RudiC did a better job of guessing what you wanted than the rest of us who thought you just wanted to reformat your input file from comma separated fields on a line to fields with labels on multiple lines as shown in your example.