Saturday, 16 April 2016

How to read data from CSV file ?


Example 1

Sample data in file "xyz.csv"
01,Shahnawaz,29,Delhi,2009
02,Rahul,24,Gurgaon,2012

Script to read the data from comma separated file
IFS=","
while read empId name age city joiningdate
   echo "Employee ID : $empId"
   echo "Name: $name"
done< xyz.csv
unset IFS

Here, comma ( , ) is Internal Field Separator (IFS) variable. Any other symbol like pipe or colon may also be used.
After doing your work, you must restore the value of IFS using unset command.


Example 2

Sample data in file /data/domains.txt
genius.edu|201.54.1.10|/home/httpd|user2024
genius.com|202.54.1.20|/home/httpd|user2025

Script to read the data from pipe separated file
file=/data/domains.txt
IFS='|'
while read -r domain ip webroot username
do
   echo  "Domain : $domain"
   echo  "IP address : $ip"

done < "$file"
unset IFS

No comments:

Post a Comment

Note: only a member of this blog may post a comment.