substr in awk statement from xml parse

℡╲_俬逩灬. 提交于 2019-12-06 21:42:51
John1024

Because your keys here are of different length, the substr approach is less than optimal. Try:

awk -F'[<>]' '/Name/{n=$3;t="Test"; if(n ~ /^STKPR/) t="Prod"; if (n ~/^STKSVBLKU/) t="Prod"; if (n ~/^STKSVBLOCK/) t="Prod"} /SessionHost/+/Host/{print t, n, $3;}' sample.xml |sort -u
Test STKSPRDAPP01111 10.0.0.111

How It Works

In this case, the type, denoted by t, is set according to a series of if statements. From the above code, they are:

t="Test"
if (n ~ /^STKPR/) t="Prod"
if (n ~ /^STKSVBLKU/) t="Prod" 
if (n ~ /^STKSVBLOCK/) t="Prod"

By setting t="Test", Test becomes the default: the type will be Test unless another statement matches. If of the following statements looks at the string that begins the host name and, if there is a match, sets type t to a new value. (When a regular expression begins with ^, that means that what follows must match at the beginning of the string.)

Alternative using fancier regular expressions

Since the above three if statements are all for the Prod type, the three of them could, if you preferred, be rearranged to:

t="Test"
if (n ~ /^STK(PR|SVBLKU|SVBLOCK)/) t="Prod"

(metalcated: Fixed unmatched parentheses bracket)

The substr portion produces a string containing the last character of the string. This is because it is taking a substring of string name starting at the position length(name) going to the end of the string, and because substr is indexed starting at 1.

To match whole strings you can use your variable name rather than processing it with substr.

/Name/ { name=$3; type=a[name]; if (length(type)==0) type="Test"; }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!