add header with awk
5
0
Entering edit mode
5.6 years ago
Sam ▴ 150

Dear All

I filtered a tab file with this command

awk -F'\t' '$15~/NO/' famliy.txt

but I want add header of input file to the out file with filtering command (one line command).

Thanks

awk • 9.2k views
ADD COMMENT
3
Entering edit mode
5.6 years ago

Assuming the header is the first line of the file:

cat <(head -n 1 famliy.txt) <(awk -F'\t' '$15~/NO/' famliy.txt) > output
ADD COMMENT
3
Entering edit mode
5.6 years ago
$ cat secret_family.txt 
header  header1
No  NO
No  Yes
no  no
yes No
yes NO

$ awk -F'\t'  'NR == 1 {print;next} $2 ~/NO/ ' secret_family.txt
header  header1
No  NO
yes NO

*if header doesn't contain "NO",  
$ awk -F'\t'  'NR == 1 {print} $2 ~/NO/ ' secret_family.txt

$ awk -F'\t'  'NR == 1 {print;next} NR>2 && $2 ~/NO/ ' secret_family.txt
header  header1
yes NO

$ awk -F'\t'  '{IGNORECASE=1};NR == 1 {print;next} NR>2 && $2 ~/NO/ ' secret_family.txt
header  header1
no  no
yes No
yes NO
ADD COMMENT
1
Entering edit mode

same thing can be done with ebay tsv-utils input:

$ cat secret_family.txt 
header  header1
No  NO
No  Yes
no  no
yes No
yes NO

case sensitive filtering of 2nd column with header:

$ tsv-filter -H --str-eq 2:NO secret_family.txt 
header  header1
No  NO
yes NO

case insensitive filtering of 2nd column with header:

$ tsv-filter -H --istr-eq 2:NO secret_family.txt 
header  header1
No  NO
no  no
yes No
yes NO
ADD REPLY
1
Entering edit mode
5.6 years ago
Ram 43k

Hard-code it in using a conditional on NR or combine this command with a separate preceding head command. Also, please explain how this is related to bioinformatics.

EDIT: More information.

awk has builtin variables, one of which is NR (the current record-number). This can be used as a proxy for line-number when the record separator is a new line. If your header is of constant length and in the same position at the top of the file, you can effectively use line numbers to write conditions. awk 'NR<3 { print }' in_file would print the first 2 lines of the file in_file. This can also be achieved with the command head -n 2 in_file.

ADD COMMENT
1
Entering edit mode
5.6 years ago
Tm ★ 1.1k

I am not sure about awk, but then you can use below mentioned sed command followed by your command to add header to your new file generated. This consider the fact that your header is the 1st line of your file "family.txt" file.

sed '1q;d' famliy.txt >famliy_R1.txt | awk -F'\t' '$15~/NO/' famliy.txt >>famliy_R1.txt
ADD COMMENT
1
Entering edit mode

What's the reasoning behind using the pipe here? Wouldn't a ; or a && be better suited given that no output piping occurs?

ADD REPLY
0
Entering edit mode

yes, you are very much right.

ADD REPLY

Login before adding your answer.

Traffic: 2528 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6