Awk match pattern default

HI friends,

pls help me with the simple logic not able to hit at this moment.
If both DEPARTMENT & BU are present in file print/take only DEPARTRMENT value or else print/take BU value

input file 1:

DEPARTMENT: A
BU: XYZ

output

A

Input file 2

BU: 123

Output

123

I tried something like below it is printing both, please suggest. In jinja we use default keyword for this.

awk '{if (/^DEPARTMENT /) {print $2} else if (/^BU/) { print $2} }' inputfile

egards

Hi @pradyumnajpn10

Please edit your post according to the forum guidelines, here:

Thanks.

I am thinking to use flag like below

awk 'BEGIN{n=0} {if (/^DEPARTMENT) { print $2; n=1 } else if(/^BU/) {if (n!=1) print $2 } }' inputfile

please suggest if something better..

Please wrap your code in markdowns!

Storing "delayed" values and/or statuses in variables is the right idea.
Your implementation requires that a BU, if present, must occur after a DEPARTMENT.
Otherwise you would need to further delay the conditional printing, perhaps up to an END section if DEPARTMENT can occur on the very last line.

Thank you MADEINGERMANY for the right direction.. I will proceed with this logic..
Yes the sequence is DEPARTMENT comes first. DEPARTMENT and then BU.
But using END is more secure as suggested I guess..

This topic was automatically closed 300 days after the last reply. New replies are no longer allowed.