I have a csv file with the values seperated by commas.I want to extract these values one by one and assign to a variable using shell script.Any ideas or code?
You need to post a sample from your file. 2-3 lines will do.
I would tell you to directly read the fields into variables by changing the IFS variable, but it would be better if you could give a sample.
sample file name:sitenames.csv
www.real.com,324kb,1,MyPlace
www.yahoo.com.423kb,2,Mysite,Public site
Datas will be in this form
Not able to open the sample file
i have just put the content of the sample file which is seperated by commas.Not attached any file..
assuming sitenames.csv
www.real.com,324kb,1,MyPlace
www.yahoo.com,423kb,2,Mysite,Public site
#!/bin/ksh
while IFS=, read site space number name
do
echo "site -> [${site}]"
echo "space -> [${space}]"
echo "number -> [${number}]"
echo "name -> [${name}]"
done < sitenames.csv
What if number of fields are not known and they vary among the lines
how do we capture and print them as shown above
while IFS=, read site space number . . . . . ( n number of fields )
not using this paradigm.
read the entire 'line' into a variable, figure out how MANY fields there and assign them appropriately knowing the name/variable of every field number.
Others may have other ideas.
If the fields vary that much, and if this file is relatively large, use awk.
Another way is store in dictionary/hash. eg Python
>>> d = {}
>>> for lines in open("input.txt"):
... all = lines.strip().split(",")
... d[all[0]] = all[1:]
...
>>> d
{'www.real.com': ['324kb', '1', 'MyPlace'], 'www.yahoo.com': ['423kb', '2', 'Mysite', 'Public site']}
>>>
I noticed you used ksh should this work in a bash
#!/bin/ksh
oIFS="$IFS"
while read str
do
# delimeter ,
IFS=","
# parse str to the array flds using delimeter $IFS
set -A flds -- $str
IFS="$oIFS" # return org IFS
cnt=${#flds
[*]} # number of values
#1st field value is value of flds[0]
# print "1st fld value = ${flds[0]} "
done < sitenames.csv