Extract line from file using shell script

I have a CSV file with columns as shown below,

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

      

I need to extract a row by column "Env" or "User". script 'extract.sh' I wrote:

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 three parameters like sh extract.sh username.csv dev 3 . The first parameter is the csv file, the second is the value, and the third is column no, the output I get is

User Name Env Role
user1 pap dev  dev

      

But I need an output like this,

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

      

Can anyone help me with this?

+3


source to share


1 answer


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

      

+3


source







All Articles