Reading a csv file using shell script

Hello All,
I have a csv file that looks like below

ProdId_A,3.3.3,some text,some/text,sometext_1.2.3
ProdId_B,3.3.3,some text,some/text,sometext_1.2.3
ProdId_C,3.3.3,some text,some/text,sometext_1.2.3
ProdId_A,6.6.6,some text,some/text,sometext_9.9.9

I will get ProdId from user.I need to write a script that will find a match from entries above.Search should start from last entry and go upward.

For example if I get "ProdId_A" from user I should be able to get other values like 6.6.6 , 9.9.9.

Thanks in advance !!!

prod='ProdId_A';
awk -F, -v what="$prod" '$1==what{split($5,b,"_");a=$2 FS b[2]}END{print a}' file
1 Like

Dear
Can you please elaborate your answer ???? If I want to hold other column values of same row,How can I do it ???E.g. In above csv file, if I want to hold 6.6.6. and sometext_9.9.9, HOw can I do it ????

The awk command searches for a record whose first field ($1) matches the variable value supplied (variable what containing ProdId_A ). For each such record, the split function is used to get, e.g., 9.9.9 from sometext_9.9.9 . This combination (field 2 and the value from the last operation) is stored in the variable a . This is printed at the end of the file to emulate searching the first record from the bottom of the file.

1 Like

Hey friend,
Thank u very much !!! the problem is I am not able to assign the value of "a" to any variable neither "a" is accessible outside the END block.

Using the file text.txt with the above content I used these commands :

prod=ProdId_A
cat text.txt | grep $prod | cut -d "," -f2 | sort -r
6.6.6
3.3.3

And got this output. If I understood correctly what you want, otherwise you'll have to explain it better. However if the file is very large these shell commands will be very slow, and in this case I suggest to use/adapt the awk approach presented earlier in this thread.