Print XML element with AWK

后端 未结 2 1724
情书的邮戳
情书的邮戳 2021-01-21 10:03

How do I print the contents of an XML element - from the starting tag to the closing tag - using AWK?

For example, consider the following XML:



        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 10:36

    $ awk -v tag='city' '$0~"^<"tag"\\>"{inTag=1} inTag; $0~"^"{inTag=0}' file
    
           Athens
           GA
            Home of the University of Georgia
           100,000
           Located about 60 miles Northeast of Atlanta
           33 57' 39" N
           83 22' 42" W
    
    

    Using GNU awk above for \> word boundary functionality. With other awks use [^[:alnum:]_] or similar.

    To only print the first occurrence:

    $ awk -v tag='city' '$0~"^<"tag"\\>"{inTag=1} inTag{print; if ($0~"^") exit}' file
    
           Athens
           GA
            Home of the University of Georgia
           100,000
           Located about 60 miles Northeast of Atlanta
           33 57' 39" N
           83 22' 42" W
    
    

提交回复
热议问题