You're viewing a comment by Jaypal and its responses.

June 01, 2013, 20:48

Hi Peteris,

The 3 books are great and have been of great help in learning idiomatic way of writing. I have a question. Though it is a bit rhetorical. :)

I want to use a ternary operator without the else condition. Something like

(test condition) ? do this : do nothing

Example:

[jaypal:~/Temp] cat test
aa
bb
bb
aa
aa
xx
aa
ff
gg
ss
ff
gg
[jaypal:~/Temp] awk '{ a[$1]++} END { for (k in a) print (a[k]<2) ? k : "" }' test

ss

xx

I don't want awk to print blank lines. So how to do I tell it not to do anything if test is not true. Something like continue is used in loops.

Keep up the good work. Your blogs makes complex things look easy. God bless.

Comment Responses

Jaypal Singh Permalink
June 01, 2013, 21:11

I did this but not sure if this is the best way to avoid the else condition.

[jaypal:~/Temp] awk '{ a[$1]++ } END { for (k in a) printf (a[k]<2) ? k"\n" : null }' test
ss
xx

July 05, 2013, 17:57

Here is how:

awk '{ a[$1]++ } END { for (k in a) if (a[k]<2) printf k"\n" }'

You simply replace the ternary operator with if.

March 05, 2014, 22:01

Yep, thats what I usually use. I wanted to know if there is a way we can use ternary operator and not define the else condition. Do we need to have both conditions explicitly stated? I know it sounds a bit rhetorical, but I just wanted to know if there is an idiomatic way of using ternary but not specifying else condition.

Keep up the good work! Your perl and awk ebooks are classic! Can't wait for bash one-liner! :)

Reply To This Comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the word "linux": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.