Extract string from bash output

Viewed 48

I want to extract the server for which the query gave the result. From the below output, I have to extract the server name 'TSMPDC1'

ANR1687I Output for command 'QUERY NODE pdviateng017' issued against server CSNDCTSMP008 follows:
ANR2034E QUERY NODE: No match found using this criteria.
ANR1687I Output for command 'QUERY NODE pdviateng017' issued against server TSMNDC18 follows:
ANR2034E QUERY NODE: No match found using this criteria.
ANR1687I Output for command 'QUERY NODE pdviateng017' issued against server TSMPDC1 follows:

Node Name                     Platform     Policy Domain      Days Sinc-     Days Sinc-     Locked?
                                           Name                  e Last      e Passwor-     
                                                                  Access          d Set     
-------------------------     --------     --------------     ----------     ----------     -------
XXXXXXXXXXXX                  Linux        DM_DECOMM                  <1             67       No   
                               x86-64                                                              
ANR1687I Output for command 'QUERY NODE pdviateng017' issued against server TSMIDC7 follows:
ANR2034E QUERY NODE: No match found using this criteria.

I tried using the following command:

my_command | awk '/ANR1687I/{f=1} /Node Name/{f=0} f' | awk '/server/{f=1} /follows/{f=0} f'

But I'm getting empty output.

1 Answers

A simplified awk:

awk '$1=="ANR1687I" && $NF=="follows:" {s=$(NF-1)} /Node Name/ {print s; exit}' file

TSMPDC1

Explanation:

awk '
if $1 is "VANR1687I and last field i.e. $NF is "follows:"
$1=="ANR1687I" && $NF=="follows:" {
   s = $(NF-1)  # set variable s to value in last-1 field i.e. $(NF-1)
}
/Node Name/ {   # if line has text "Node Name"
   print s      # print variable s
   exit         # exit awk command
}' file
Related