Chinaunix

标题: awk 匹配抽取段平替换指定字符 [打印本页]

作者: nakalzz    时间: 2012-11-19 21:45
标题: awk 匹配抽取段平替换指定字符
今天工作遇到以下问题还望高手多多指教
  1. <?xml version="1.0"?>
  2. <food>
  3. <name>Belgian Waffles</name>
  4. <price>5</price>
  5. <description>
  6. two of our famous Belgian Waffles with plenty of real maple syrup
  7. </description>
  8. <calories>650</calories>
  9. </food>
  10. ....
  11. ....
  12. ....
  13. </xml>
  14. <?xml version="1.0"?>
  15. <food>
  16. <name>Strawberry Belgian Waffles</name>
  17. <price>7</price>
  18. <description>
  19. light Belgian waffles covered with strawberries and whipped cream
  20. </description>
  21. <calories>900</calories>
  22. </food>
  23. </xml>

  24. 1 抽取calories是900的段也就是抽取如下段
  25. <?xml version="1.0"?>
  26. <food>
  27. <name>Strawberry Belgian Waffles</name>
  28. <price>7</price>
  29. <description>
  30. light Belgian waffles covered with strawberries and whipped cream
  31. </description>
  32. <calories>900</calories>
  33. </food>
  34. </xml>

  35. 2 匹配
  36. price 为5 calories为900时候name替换为GOD

  37. 还望高手多多指教
复制代码

作者: yinyuemi    时间: 2012-11-19 22:09
回复 1# nakalzz
  1. awk '/^<\?xml/{t=$0}{t=t RS $0}/<\/xml/{if(t~"<calories>900<"){print t};t=""}' file


  2.     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
  1. 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