amit
amit

Reputation: 10261

unable to run awk command as a shell script

i am trying to create a shell script to search for a specific index in a multiline csv file. the code i am trying is:

#!/bin/sh

echo "please enter the line no. to search: "
read line

echo "please enter the index to search at: "
read index

awk -F, 'NR=="$line"{print "$index"}' "$1"

the awk command I try to use on the shell works absolutely fine. But when I am trying to create a shell script out of this command, it fails and gives no output. It reads the line no. and index. and then no output at all. is there something I am doing wrong?

I run the file at the shell by typing:

./fetchvalue.sh newfile.csv

Upvotes: 0

Views: 518

Answers (2)

Andrew Beals
Andrew Beals

Reputation: 1187

Rather than going through quoting hell, try this:

awk -F, -v line=$line -v myindex=$index 'NR==line {print $myindex}' "$1"

(Index is a reserved word in awk, so I gave it a slightly differet name)

Upvotes: 0

Mat
Mat

Reputation: 206679

Your quoting is not going to work. Try this:

awk -F, 'NR=="'$line'"{print $'$index'}' "$1"

Upvotes: 1

Related Questions