How to not remove the header while executing awk

Viewed 127

I have a file file like this :

k_1_1
k_1_3
k_1_6
...

I have a file file2 :

0,1,2,3,...
k_1_1,17,16,15,...
k_1_2,17,89,15,...
k_1_3,10,26,45,...
k_1_4,17,16,15,...
k_1_5,10,26,45,...
k_1_6,17,16,15,...

...

I want to print lines of file2 that is matched with fileThe desired output is :

0,1,2,3,...
k_1_1,17,16,15,...
k_1_3,10,26,45,...
k_1_6,17,16,15,...

I tried

awk 'BEGIN{FS=OFS=","}NR==FNR{a[$1];next}$1 in a {print $0}' file file2 > result

But the header line is gone in result like this :

k_1_1,17,16,15,...
k_1_3,10,26,45,...
k_1_6,17,16,15,... 

How can a maintain it? Thank you.

3 Answers

Always print the first line, unconditionally.

awk 'BEGIN{FS=OFS=","}
    NR==FNR{a[$1];next}
    FNR==1 || $1 in a' file file2 > result

Notice also how { print $0 } is not necessary because it's the default action.

Could you please try following.

awk -F, 'FNR==NR{a[$1]=$0;next} FNR==1 && ++count==1{print;next} a[$1]' Input_file  Input_file2

OR

awk -F, 'FNR==NR{a[$1]=$0;next} FNR==1{print;next} a[$1]' Input_file Input_file2

A very ad-hoc solution to your problem could be to compose the output in a command group:

{ head -1 file2; awk 'BEGIN{FS=OFS=","}NR==FNR{a[$1];next}$1 in a {print $0}' file file2; } > result
Related