Chinaunix
标题:
awk 匹配抽取段平替换指定字符
[打印本页]
作者:
nakalzz
时间:
2012-11-19 21:45
标题:
awk 匹配抽取段平替换指定字符
今天工作遇到以下问题还望高手多多指教
<?xml version="1.0"?>
<food>
<name>Belgian Waffles</name>
<price>5</price>
<description>
two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
....
....
....
</xml>
<?xml version="1.0"?>
<food>
<name>Strawberry Belgian Waffles</name>
<price>7</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
</xml>
1 抽取calories是900的段也就是抽取如下段
<?xml version="1.0"?>
<food>
<name>Strawberry Belgian Waffles</name>
<price>7</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
</xml>
2 匹配
price 为5 calories为900时候name替换为GOD
还望高手多多指教
复制代码
作者:
yinyuemi
时间:
2012-11-19 22:09
回复
1#
nakalzz
awk '/^<\?xml/{t=$0}{t=t RS $0}/<\/xml/{if(t~"<calories>900<"){print t};t=""}' file
awk '/^<\?xml/{t=$0}{t=t RS $0}/<\/xml/{if(t~"<calories>900<" && t~"<price>7<"){t=gensub(/(.*<name>)Strawberry Belgian Waffles(<\/name>.*)/,"\\1GOD\\2",1,t);print t};t=""}' file
复制代码
作者:
nakalzz
时间:
2012-11-19 22:28
回复
2#
yinyuemi
多谢您的热心回复
第一个我尝试了一下结果中<?xml version="1.0"?>出现两次。。
<?xml version="1.0"?>
<?xml version="1.0"?>
<food>
<name>Strawberry Belgian Waffles</name>
<price>7</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
</xml>
第二个name中间的内容不是固定的不知道有什么好的匹配方法
还请多多指教
作者:
yinyuemi
时间:
2012-11-19 22:35
回复
3#
nakalzz
awk '/^<\?xml/{t=$0}{t=t RS $0}/<\/xml/{if(t~"<calories>900<" && t~"<price>7<"){t=gensub(/(.*<name>)[^<>]+(<\/name>.*)/,"\\1GOD\\2",1,t);print t};t=""}' file
复制代码
作者:
yestreenstars
时间:
2012-11-19 23:32
本帖最后由 yestreenstars 于 2012-11-20 00:06 编辑
回复
3#
nakalzz
@yinyuemi
/^<\?xml/{t=$0}这句改成/^<\?xml/{t=$0;next}
作者:
dwj19830118
时间:
2012-11-19 23:34
1.
cat file | awk '/<?xml/,/<\/xml>/{ print}' | awk '$0!="</xml>"{t=t$0;next;}{print t$0;t=""}' | grep 900
2.
cat file | awk '/<?xml/,/<\/xml>/{ print}' | awk '$0!="</xml>"{t=t$0;next;}{print t$0;t=""}' | sed 's/\(.*<\)name\(>.*<\/\)name\(><price>5<\/price>.*<calories>900<\/calories>.*\)/\1god\2god\3/g'
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2