How to keep the header of the file when filtering using awk

Viewed 323

I have a file that looks like this with a header. I am just showing the first 8 columns although there are 26 columns.

id  Id  Study   Site    CancerType  Sex Country unexpected_duplicates
468768  1032    Response    Karlburg    VN  Breast  Female  Germany 
468769  1405    Response    Santiago        Prostate  Male  Spain   

I want to filter the Cancer type (column 5) by "Breast" using this command which works fine:

awk '($5 == "Breast")' PCA.covar > PCA.covar1

The only problem is my header is not printed and the first line is missing in the output.

So I modified my command to:

awk 'NR==1; NR > 1 ($5 == "Breast")' PCA.covar > PCA.covar1

And I see that while the header is there, it has not filtered by Breast:

id  Id  Study   Site    CancerType  Sex Country unexpected_duplicates
468768  1032    Response    Karlburg    VN  Breast  Female  Germany 
468769  1405    Response    Santiago        Prostate  Male  Spain  
68772  RQ56001-9 Response   Maastricht      Prostate  Male  Netherlands 

1 Answers

This should do it:
awk 'NR==1 || $5 == "Breast"{print}' PCA.covar > PCA.covar1

Related