3

I have a CSV file, with the columns like below,

User     Name   Env   Role
user1    pap    dev    dev
user2    nic    uat    test

I need to extract a row, with respect to either the column 'Env' or 'User'. The script 'extract.sh' I have written is,

k=$2
field=$3
head -1 $1; cat $1 | awk -F "," -v k=`echo $k` -v field=`echo $field` '{ k=k;j=$field; if ( j==k )  print $0}'

The script is called with 3 parameters like this , sh extract.sh username.csv dev 3 the first parameter is csv file the second is the value and the third is column no, the output i am getting is

User Name Env Role
user1 pap dev  dev

But I need the output like this,

User = user1 
Name = pap
Env = dev
Role = dev

Could anyone please help me in getting this ?

1
  • 1
    You're doing too much work assigning the awk variables: -v k="$k" -v field="$field" Commented May 7, 2015 at 11:02

1 Answer 1

3

You can use this awk:

awk -F, -v RS='\r\n' -v col=$3 -v val="$2" 'NR==1 {for (i=1; i<=NF; i++) hdr[i]=$i;next}
             $col == val {for (i=1; i<=NF; i++) print hdr[i], "=", $i; exit}' "$1"
User = user1
Name = pap
Env = dev
Role = dev

Explanation:

NR == 1      # For first row save headers in an array called hdr
$col == val  # when passed val is same as the value of column indicated by col
Sign up to request clarification or add additional context in comments.

7 Comments

May I know how you are passing the filename parameter ?
I am not getting output and also no errors. Any idea ?
Run this awk directly from command line like this: awk -v col=3 -v val='dev' 'NR==1{for (i=1; i<=NF; i++) hdr[i]=$i; next} $col == val {for (i=1; i<=NF; i++) print hdr[i], "=", $i; exit}' file. This gives me output attached in answer.
I have tried it as command also, but the same problem. Couldn't figure out.
That means your file is not same as shown in question. Using cat -vte file check whether you have DOS line ending. If yes then run dos2unix to convert to unix file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.