awk to match condition and print in columns

Dear team,

Need support for below request.

Input file

The below code executed successful which check AdminState=UNLOCKED and if not it prints.

awk -F'=|,| ' 'BEGIN{
  print "Checking PL AND SC AMF STATUS:"
}
/safAmfNode/{
  if (a["AdminState"]!~"UNLOCKED") print a["safAmfNode"],a["AdminState"];
  delete a
}
/safAmfNode/{ FS=",";
  a["safAmfNode"]=$1;
  next
}
/AdminState/{ FS=",";
  a["AdminState"]=$1;
  next
}
/OperState/{
  a["OperState"]=$1;
  next
}

END{
  if (a["AdminState"]!~"UNLOCKED") print a["safAmfNode"],a["AdminState"];
}
' OFS=","   TESTFILE

Output as below

As soon as i print this a["OperState"] array in output. The Output distorted as below.

awk -F'=|,| ' 'BEGIN{
  print "Checking PL AND SC AMF STATUS:"
}
/safAmfNode/{
  if (a["AdminState"]!~"UNLOCKED") print a["safAmfNode"],a["AdminState"],a["OperState"];
  delete a
}
/safAmfNode/{ FS=",";
  a["safAmfNode"]=$1;
  next
}
/AdminState/{ FS=",";
  a["AdminState"]=$1;
  next
}
/OperState/{ FS=",";
  a["OperState"]=$1;
  next
}

END{
  if (a["AdminState"]!~"UNLOCKED") print a["safAmfNode"],a["AdminState"],a["OperState"];
}
' OFS=","   TESTFILE

Distorted Output as below

instead

Thanks in advance.

Hello shanul karim,

Thank you for sharing your efforts in form of code in your question. Could you please do let us know more clearly what is the logic of getting the expected output. Honestly its not clear(at least to me :slight_smile: )

Kindly do add the same and let us know then.

Thanks,
R. Singh

1 Like

I'm glad I'm not the only one having difficulties with the OP's specification, even though this one - being the third on the same topic - has way more details than the former ones.

The problem you encounter likely has to do with DOS line terminators (<CR> = ^M = \r = 0x0D) in the input file. This is what I get from your code with a "clean" input:

Checking PL AND SC AMF STATUS:
,,
safAmfNode=PL-13,AdminState=LOCKED(1),OperState=ENABLED(1)

, as opposed to what a "contaminated" input yields:

Checking PL AND SC AMF STATUS:
,,
,OperState=ENABLED(1)nState=LOCKED(1)

Let me add that your approach - although working - has quite some potential for improving. Pls check this aprroach:

awk -F, '
BEGIN                   {print "Checking PL AND SC AMF STATUS:"
                        }

                        {gsub ("\r", "")
                        }

/^safAmfNode/           {TMP = $1
                        }
/^AdminState/ &&
!/UNLOCKED/             {getline OP
                         print TMP, $0, OP
                        }
' OFS="," file
Checking PL AND SC AMF STATUS:
safAmfNode=PL-13,AdminState=LOCKED(1),OperState=ENABLED(1)