chas
chas

Reputation: 1655

How to run if condition only on certain columns in awk

I have a file with columns as shown below:

row1  0.15  0.03
row2  0.06  0.028
row3  0.05  0.05
row4    
row5        0.09    
row6    

I want to filter the file by removing rows if values in col2=col3. This is quiet simple condition to write '$2=$3'. But, when $2=$3 condition is applied, rows with blank values in col2 and col3 are also filtered. I would like this condition to be run on only rows which has values. Sample output shown below. Only row 3 is filtered. Even though also meets the condition it does not have any integer values.

row1  0.15  0.03
row2  0.06  0.028
row4    
row5        0.09    
row6

I know it is something simple but it does not work when i tried in the below way and also few other ways, it prints the original file.

awk -F '\t' '$1!="" && $2!= "" {$1==$2}1' OFS="\t"

Upvotes: 0

Views: 90

Answers (1)

Wintermute
Wintermute

Reputation: 44063

With awk:

awk -F '\t' -v OFS='\t' '$2 == "" || $2 != $3' filename
  • The code $2 == "" || $2 != $3 is just a condition, so the default action (printing) is performed if it is true.
  • An explicit check for $3 == "" is not necessary because either $2 == "" or $2 != $3 is true in that case.

Upvotes: 3

Related Questions