Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: select first column and value in column after matching word

I have a .csv where each row corresponds to a person (first column) and attributes with values that are available for that person. I want to extract the names and values a particular attribute for persons where the attribute is available. The doc is structured as follows:

name,attribute1,value1,attribute2,value2,attribute3,value3
joe,height,5.2,weight,178,hair,
james,,,,,,
jesse,weight,165,height,5.3,hair,brown
jerome,hair,black,breakfast,donuts,height,6.8

I want a file that looks like this:

name,attribute,value
joe,height,5.2
jesse,height,5.3
jerome,height,6.8

Using this earlier post, I've tried a few different awk methods but am still having trouble getting both the first column and then whatever column has the desired value for the attribute (say height). For example the following returns everything.

awk -F "height," '{print $1 "," FS$2}' file.csv

I could grep only the rows with height in them, but I'd prefer to do everything in a single line if I can.

like image 863
HJT Avatar asked Oct 11 '25 12:10

HJT


1 Answers

You may use this awk:

cat attrib.awk

BEGIN {
   FS=OFS=","
   print "name,attribute,value"
}
NR > 1 && match($0, k "[^,]+") {
   print $1, substr($0, RSTART+1, RLENGTH-1)
}

# then run it as
awk -v k=',height,' -f attrib.awk file

name,attribute,value
joe,height,5.2
jesse,height,5.3
jerome,height,6.8

# or this one
awk -v k=',weight,' -f attrib.awk file

name,attribute,value
joe,weight,178
jesse,weight,165
like image 97
anubhava Avatar answered Oct 14 '25 20:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!