5

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.

Birei
  • 35,723
  • 2
  • 77
  • 82
Kaptain K
  • 57
  • 1
  • 1
  • 4

3 Answers3

15

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
Scrutinizer
  • 9,608
  • 1
  • 21
  • 22
  • using this I would be able to read the variables individually. I would be able to return them individually but I would want them to read by row. For example if I call row 2 using a variable P2 (say)It should be able to return MAC(2), DN(2) etc – Kaptain K Mar 11 '13 at 23:31
0

Using awk :

read -p "Gimme the DN integer >>> " i
awk -v i=$i -F' , ' '
    NR>1{
        dn[NR]=$1
        mac[NR]=$2
        partition[NR]=$3
    }
    END{
        for (a=2; a<=NR; a++)
            if (i == dn[a])
                print dn[a], mac[a], partition[a]
    }
' file.txt
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

you can also try this

file1 stores all the DN for which you want to retrieve the information

#parse.awk

BEGIN { FS="," ; OFS= "\t"}

FNR==NR{ a[$1]; next }

$1 in a { print $1,$2,$3}

call awk -f parse.awk file1 csvfile.csv

WYSIWYG
  • 494
  • 6
  • 23