let's consider the following example

1 4.0 3.5 7.2
2 3.2 2.5 5.2
3 1.7 -1.8 2.9
4 4.1 2.5 5.7

How can I extract the 3rd column of the table by ignoring the negative number?

If I use awk '{print $3}' filename, it will give me all the four numbers. But I want to take only positive numbers, i.e. the final output must be three numbers:


How can I do that?


3 Answers 3


Assuming that the input is purely numeric, as shown in the question:

awk '$3 >= 0 { print $3 }' file

The test in front of the block determines whether the block will run. In this case, the test is an arithmetic test which will be true if the data in the 3rd field is a non-negative number. When this is the case, that field is outputted.


It's possible to treat the third column either as a number or as a string. awk has implicit conversion from string to number if the context requires it, with non-numeric values equated to zero and non-numeric suffixes being ignored.

In this solution there is no numeric comparison. The string is checked to see that it does not begin with a minus symbol, -, and is output only if so:

awk '$3 !~ /^-/ {print $3}' filename

(This solution will skip the value if it begins with - even if it is not a negative number. For example --00. Modifying the RE or forcing a numeric comparison may address that. If you have only numeric values then this issue will not arise.)

awk '$3 ~/^[0-9]/{print $3}' file.txt 



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.