简体   繁体   English

awk match如何传递第三个参数

[英]awk match how to pass 3rd argument

Am trying to add a 3rd column/argument to achieve my output. 我正在尝试添加第三列/参数来实现我的输出。 In the below data/string I would like to add the "type" to my existing output 在下面的数据/字符串中,我想在现有输出中添加“类型”

Data:
<field name="AVERAGE_TIME" type="float" id="0xDZZ" sequence="1"/>


Present working script
FILE="$1"
awk -F[=\ ] 'BEGIN{OFS="|" }
/context/{cn=$3}
/field/{match($0,"id=[^ ]+"); idstart = RSTART+3; idlen=RLENGTH-3;
match($0,"name=[^ ]+"); namestart=RSTART+5; namelen=RLENGTH-5;
print substr($0,namestart, namelen), substr($0,idstart, idlen),cn
}' "../$FILE" |  sed 's/\"//g' 


Present Output
AVERAGE_TIME|0xDZZ|temp


What I would like to see (type added)
 AVERAGE_TIME|0xDZZ|temp|float
$ awk -F'"' -v OFS='|' '{print $2, $6, "temp", $4}' file
AVERAGE_TIME|0xDZZ|temp|float

If that doesn't do what you want then please edit your question to clarify your requirements and add some more truly representative sample input and expected output. 如果这样做不能满足您的要求,请编辑您的问题以阐明您的要求,并添加一些更具有代表性的示例输入和预期输出。

Here's how you'd modify your original script to do what you need. 这是修改原始脚本以执行所需操作的方式。 Here's the unchanged part: 这是未更改的部分:

FILE="$1"
awk -F[=\ ] 'BEGIN{OFS="|" }
/context/{cn=$3}
/field/{match($0,"id=[^ ]+"); idstart = RSTART+3; idlen=RLENGTH-3;
match($0,"name=[^ ]+"); namestart=RSTART+5; namelen=RLENGTH-5;

Now, we add an addditional line and modify the print: 现在,我们添加一条附加线并修改打印内容:

match($0,"type=[^ ]+"); typestart=RSTART+5; typelen=RLENGTH-5
print substr($0,namestart, namelen), substr($0,idstart, idlen),cn,substr($0,typestart,typelen)
}' "../$FILE" |  sed 's/\"//g' 

Just a note, awk is not a good solution for xml-parsing and your awk script isn't the best way of doing it either. 请注意,awk对于xml解析不是一个好的解决方案,您的awk脚本也不是做到这一点的最佳方法。 Here's a slightly-cleaner solution, if you really need to use awk here (I just copied your context stuff verbatim here): 如果您确实需要在这里使用awk,这是一个稍微干净的解决方案(我只是在这里逐字复制了您的上下文内容):

cat $FILE | 
awk  'BEGIN{OFS="|" } 
     /context/{cn=$3} ## i just copied this verbatim from your script
     /^<field/ && NF>3 {delete x; 
                       for (i=1; i<=NF; i++) {  
                          match($i,  /^(.*?)=\"(.*?)\"$/, arr); 
                          if (1 in arr && 2 in arr) { x[arr[1]] = arr[2];}
                        }; 
                        print x["name"], x["id"], cn, x["type"]}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM