HJT*_*HJT 3 bash awk text-processing sed
我有一个 .csv,其中每一行对应一个人(第一列)以及具有该人可用值的属性。我想提取该属性可用的人员的特定属性的名称和值。该文档的结构如下:
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
Run Code Online (Sandbox Code Playgroud)
我想要一个如下所示的文件:
name,attribute,value
joe,height,5.2
jesse,height,5.3
jerome,height,6.8
Run Code Online (Sandbox Code Playgroud)
使用这篇之前的文章,我尝试了几种不同的awk方法,但仍然无法获取第一列和任何具有所需属性值(例如高度)的列。例如以下内容返回所有内容。
awk -F "height," '{print $1 "," FS$2}' file.csv
Run Code Online (Sandbox Code Playgroud)
我grep只能处理具有高度的行,但如果可以的话,我更愿意在一行中完成所有操作。
你可以使用这个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
Run Code Online (Sandbox Code Playgroud)