birac
birac

Reputation: 598

Use awk to find all columns which contain values above and below specified numbers?

I would like an Awk command where I can search a large file for columns which contain numbers both below 3 and above 5. It also needs to skip the first column.

e.g. for the following file

   1 2 6 2
   2 1 7 3
   3 2 5 4
   4 2 8 7
   5 2 6 8
   6 1 9 9

In this case, only column 4 is a match, as it is the only column with values above 5 and below 3 (except for column 1, which we skip).

Currently, I have this code:

 awk '{for (i=2; i<=NF; i++) {if ($i < 3 && $i > 5) {print i}}}'

But this only reads one row at a time (so never makes a match). I want to search all of the rows, but I am unable to work out how this is done.

Ideally the output would simply be the column number. So for this example, simply '4'.

Many thanks.

Upvotes: 1

Views: 920

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following and let me know if this helps you.

awk '{for(i=1;i<=NF;i++){if($i<3){col[i]++};if($i>5){col1[i]++}}} END{for(j in col){if(col[j]>=1 && col1[j]>=1){print j}}}'  Input_file

If you want to start searching from second column then change i=1 to i=2 in above code.

EDIT: Adding a non-one liner form of solution too now.

awk '
{
  for(i=1;i<=NF;i++){
    if($i<3)                   {  col[i]++ };
    if($i>5)                   {  col1[i]++}}
}
END{
  for(j in col){
    if(col[j]>=1 && col1[j]>=1){  print j  }}
}'  Input_file

Upvotes: 1

Related Questions