awk three conditions

I'm having a problem pulling UID's from data. The data outputs a user's UID in one of three ways:

1. Error User user_name already assigned with <UID>
2. Success <UID> reserved for user_name
3. <a load of crap because there was a db failure yet somehow the UID is still in there>

I typically used an awk statement to pull out the UID until item 3 started happening which I cannot control. If the first word of the output said "Success" then the UID was always in value 12. If the first word was "Error" then the UID was value 7, but I wouldn't bother checking for "Error" I would just look for "Success" and print value 12, else print value 7 (the additional sed is just for formatting):

awk '{if ($1 == "Success") {print $12} else print $7","$NF}' txt_file | cut -d, -f2,3 | sed 's/,//g'

So fundamentally all I'm trying to do is add 1 more condition to the awk statement. I tried inserting elif and else if and I keep getting syntax errors. How can I insert that third condition?

GNU Linux using ksh.

Use "elif". It works like this (see "man awk" for details):

if( <condition> ) {
     <code>
} elif( <other condition> ) {
     <code>
} ...
else {
     <code>
}

You can have as many "elif"s as you like. This way the if-branching does the same as the case-branching.

I hope this helps.

bakunin

1 Like

Thanks - as previously stated I'm familiar w/ elif but I'm still receiving syntax errors. I believe I have followed as you have stated by placing the condition in single parenthesis and the code in single braces. Why am I receiving these errors?

awk: cmd. line:1: {if ($2 == "Success") {print $12} elif ($2 == "cannot") {print $52} else {print $7","$NF}}
awk: cmd. line:1:                                                         ^ syntax error
awk: cmd. line:1: {if ($2 == "Success") {print $12} elif ($2 == "cannot") {print $52} else {print $7","$NF}}
awk: cmd. line:1:                                                                     ^ syntax error

use

else if
1 Like

It works.Yeah of course - it had to be something ridiculous like that. Just like when I had an sftp script starting with:

 /usr/bin/sftp $SERVER << EOL

And godforbid I didn't put the corresponding EOL in the right location otherwise it was treated as a comment. I'm sure there's a reason for these things but wow...

It's supposed to treat the text inside it completely literally, to the point people have used it to archive files; it has to be very picky about where it ends.

You can make it less picky with <<-EOF ... EOF instead of <<EOF ... EOF , which will cause it to strip tabs off the front of everything inside. Only tabs, not spaces.