Read CSV column value based on column name

Hi All,

I am newbie to Unix I ve got assignment to work in unix

can you please help me in this regard

There is a sample CSV file
"Username", "Password"
"John1", "Scot1"
"John2", "Scot2"
"John3", "Scot3"
"John4", "Scot4"

If i give the column name as Password and row number as 4 the result I should get '

'Scot3'

can you please help me in writing shell script for the above

Thanks
John

What have you tried so far?

I'm assuming this is homework?

First, do you understand how to pass arguments to your script? Do you know what $1, $2 are inside your script?

Next, you need to know how to extract a specific line by number. I realize that the man pages of "sed" are confusing, so to get you going, try

sed -n '4p' 

Finally, you need to know how to extract the specific column you want, How will you do that? There are at least two general ways to approach that:

You could build a table that matches column names to a number. Your script would have something like

if [ $1 = "Username" ]
then
Column=1
elif  [ $1 = "Password" ]
then
Column=2
fi
echo $Column

More flexible would be if your script looked up the desired index by examining the first line itself. A crude method:

read line
Wanted=$1
set $line
if [ $Wanted = $1 ]
then
Column=1
... 

There are more clever ways to do that - Google for "Awk Associative Arrays" and see if that gives you any ideas in this vein.

I hope this gets you started. Let's see you write some code and we can help you over the rough spots.

Thank Tony ,

I have tried the following code giving error , please do the needful
John.csv is the file name

If i give the column name as Password and row number as 4 the result I should get '

'Scot3'

cat John.csv if [ $1 = "Username" ]
then
  Column=1
elif  [ $1 = "Password" ]
then
  Column=2
fi
echo $Column
read line
Wanted=$1
set $line
if [ $Wanted = $1 ]
then
  Column=1
else 
  echo "Hello"
fi

Thanks and Regards,
John