3

I have a table

1 1
1 0
0 1
0 0

I want to print the lines with two sets of selection criteria separated by OR.

Criteria set 1 : (Column 1 >= 1 and Column 2 = 0)

OR

Criteria set 2 : (Column 1 = 0 and Column 2 >= 1)

Expected output is

1 0
0 1

I have written something like this but didn't work

awk '($1>=1 && $2=0)||($1=0 && $2>=1) {print $0}'

What's the problem?

  • 1
    Use == for comparison, not = which is for assignment. – Wildcard Oct 8 '17 at 8:01
9

The problem is that you are using an assignment operator (=) rather than a test of equality (==). The boolean result of assigning zero to something is "false". This is why the test never succeeds.


The idiomatic awk command would be

awk '($1 >= 1 && $2 == 0) || ($1 == 0 && $ 2 >= 1)'

The { print $0 } is not needed as this is the default action for any condition that does not have an action.

If you just want to skip lines with the same values in column one and two (gives the same output for the given data):

awk '$1 != $2'

The output in both cases is

1 0
0 1
  • No awk '$1 != $2' will print a line 1 2 or if both numbers were >0, as OP stated, one of numbers must be 0 – αғsнιη Oct 8 '17 at 10:39
  • @αғsнιη That's why I was careful to formulate the text the way I did. – Kusalananda Oct 8 '17 at 10:40
2

Beside of the problem you had in your awk command using = instead of == for comparison that Kusalananda pointed that. What I understood from your input and the command you are using, you want those line when at least one of those are zero).

Assuming you don't have negative values, then you could use:

awk '($1 && !$2) || (!$1 && $2)' infile

Or even shorter (you can use - as well).

awk '($1 * !$2) + (!$1 * $2)' infile
1

Alternative egrep solution:

egrep '^([1-9][0-9]* *0|0 *[1-9][0-9]*)$' file

The output:

1 0
0 1
0

You don't need to use OR between the two you can even add more criteria just add them each on a separete line save it in a textfile eg 'criteria.awk' and run it like this : awk -f criteria.awk table.dat

here is the content of the awkscriptfile:

{
    if ($1 >= 1 && $2 == 0) print $0;
    if($1 == 0 && $2 >=1) print $0;
}

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.