Shell脚本,用于从给定输出中检索对象的状态

时间:2014-07-31 09:06:52

标签: bash perl shell awk solaris

我正在尝试使用shell脚本从下面的输出(Name字段的值和对应于它的OpState字段的值)中检索对象的状态。例如,在在输出上,'DP-UID-FSH'的状态为'up'。我想产生一个输出:

平台:Solaris上的Bash。

DP-UID-FSH is up.
DP-Cert-FSH is up.

以下是要解析以产生上述输出的文件的内容。

<ConfigState>saved</ConfigState></ObjectStatus><ObjectStatus xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<Class>HTTPSSourceProtocolHandler</Class>
<OpState>up</OpState>
<AdminState>enabled</AdminState>
<Name>DP-UID-FSH</Name>
<EventCode>0x00000000</EventCode>
<ErrorCode/>
<ConfigState>saved</ConfigState></ObjectStatus><ObjectStatus xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<Class>SLMAction</Class>
<OpState>up</OpState>
<AdminState>enabled</AdminState>
<Name>DP-Cert-FSH</Name>
<EventCode>0x00000000</EventCode>
<ErrorCode/>
<ConfigState>saved</ConfigState></ObjectStatus><ObjectStatus     xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<Class>SLMAction</Class>
<OpState>up</OpState>
<AdminState>enabled</AdminState>
<Name>shape</Name>
<EventCode>0x00000000</EventCode>
<ErrorCode/>

保存

我是shell脚本的新手,并不知道如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

Awk解决方案变得混乱,所以我只是添加另一个使用Perl的答案。我并不精通Perl,但我学得很轻松,这也可以解决它:

perl -lane '$state = (split(/[<>]/))[2] if /OpState/; print ((split(/[<>]/))[2] . " is $state.") if /<Name>/' file

输出:

DP-UID-FSH is up.
DP-Cert-FSH is up.
shape is up.

作为jaypal suggested(谢谢),因为启用了autosplit(-a),所以不需要拆分:

perl -F'[<>]' -lane '$state = $F[2] if /OpState/; print "$F[2] is $state" if /<Name>/' file

答案 1 :(得分:0)

使用GNU Awk或Mawk:

awk -v RS='<OpState>' -F '[<>]' 'NR > 1 { printf "%s is %s.\n", $9, $1 }' file

另:

awk '/OpState/ { gsub(/<\/?OpState>/, ""); s = $0; } /<Name>/ { gsub(/<\/?Name>/, ""); printf "%s is %s.\n", $0, s; }' file

又一个:

awk -F '[<>]' '/OpState/ { s = $3; } /<Name>/ { printf "%s is %s.\n", $3, s; }' file

输出:

DP-UID-FSH is up.
DP-Cert-FSH is up.
shape is up.