Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse CSV in bash and assign variables

I have a csv of the format (Working on Bash on linux)

DN , MAC , Partition ,  

123 , abc , xyz  
321 , asd , asd 

I am able to parse it using awk by using

eval MAC=($(awk -F "," '{print $1}' random.csv))

This is done for each column in the CSV and therefore I can call DN[2], MAC[2] etc individually which is manual and parses them individually.

But how can I parse the csv by row? For example : If I call for DN is 123, the corresponding MAC and Partition should also be returned.

like image 646
Kaptain K Avatar asked Dec 20 '22 08:12

Kaptain K


1 Answers

Try a loop:

while IFS=, read dn mac partition
do 
  echo "Do something with $dn   $mac and $partition"
done < file

To select a record you could use a case statement:

P2=123
while IFS=, read dn mac partition
do 
  case $dn in
    ($P2) echo echo "Do something with $dn   $mac and $partition" ;;
    (*)   echo "Do nothing" ;;
  esac
done < file
like image 68
Scrutinizer Avatar answered Dec 27 '22 06:12

Scrutinizer