4

What is the syntax of Ternary in awk command in order to write to a file when condition is seen?

Below I'm trying but getting syntax error for given inputs!

Input sample data infile.txt:

1,1,c
0,3,b
0,0,a
1,5,z
1,5,y
5,5,x

The command:

awk -F',' '{print (($1==$2)?>"success.txt": >"failed.txt")}' infile.txt
awk: {print (($1==$2)?>"success.txt": >"failed.txt")}
awk:                  ^ syntax error
awk: {print (($1==$2)?>"success.txt": >"failed.txt")}
awk:                                                ^ syntax error

I can use if/else, but want to know the same with Ternary syntax possibility and maybe where am I using redirection > wrong?

awk -F',' '{if ($1==$2) print >"success.txt";else print >"failed.txt"}' infile.txt
11

Make the ternary operator choose only the file, not the redirection:

awk -F',' '{print >(($1==$2)?"success.txt": "failed.txt")}'
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.