cebach561
cebach561

Reputation: 165

Print values less than specified number for all fields with awk

I have a tab-delimited file and I am interested in printing all values less than or equal to 1.

input data:

OG1_1908    1   1   1   1   1   
OG1_1909    1   1   1   1   1   
OG1_1910    1   1   1   1   1   
OG1_1000    5   6   6   0   0   
OG1_1001    0   0   0   13  2   
OG1_3987    1   0   1   0   0
OG1_3998    1   0   1   0   0
OG1_1002    2   7   2   1   2       
OG1_3999    1   0   1   0   0   
OG1_4000    1   0   1   0   0

Output data:

OG1_3987    1   0   1   0   0
OG1_3998    1   0   1   0   0   
OG1_3999    1   0   1   0   0   
OG1_4000    1   0   1   0   0   
OG1_1908    1   1   1   1   1   
OG1_1909    1   1   1   1   1   
OG1_1910    1   1   1   1   1

I have the following one-liner but I feel this isn't the smartest command because I specify each conditional for each field I am interested in. Is there a better awk command that could handle any number of fields for my input data file? Thank you

awk -F '\t' '{ if ( $2 <= 1 && $3 <= 1 && $4 <= 1 && $5 <= 1 && $6 <=1) print $0 }' inputfile 

Upvotes: 0

Views: 2253

Answers (3)

fedorqui
fedorqui

Reputation: 289585

Loop through all fields and skip line whenever one is >1. Then, print, which will only happen if the line was not skipped.

$ awk '{for (i=2; i<=NF; i++) if ($i>1) next } {print}' file
OG1_1908    1   1   1   1   1   
OG1_1909    1   1   1   1   1   
OG1_1910    1   1   1   1   1   
OG1_3987    1   0   1   0   0
OG1_3998    1   0   1   0   0
OG1_3999    1   0   1   0   0   
OG1_4000    1   0   1   0   0

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77095

Iterate through your fields starting from second column till end of line. If you encounter a field with value greater than 1, move to next line. If not, print the line.

$ awk '{for(i=2;i<=NF;i++)if($i>1){next}}1' file
OG1_1908    1   1   1   1   1   
OG1_1909    1   1   1   1   1   
OG1_1910    1   1   1   1   1   
OG1_3987    1   0   1   0   0
OG1_3998    1   0   1   0   0
OG1_3999    1   0   1   0   0   
OG1_4000    1   0   1   0   0

Upvotes: 3

William Pursell
William Pursell

Reputation: 212238

 awk '{p = 1; for( i = 2; i <= NF; i++ ) if ( $i > 1 ) p = 0} p'

Upvotes: 1

Related Questions