Ramon Ramon - 3 months ago 8
Bash Question

How to extract certain lines from text file by REGEX

I have this complicated text file with over 22,000 lines:

>Cluster 35
0 2856nt, >tru_clu8_1_inde2_or1... *
>Cluster 36
0 1179nt, >gl_isotig07707... *
1 914nt, >un_isotig04557... at +/94.20%
2 1282nt, >cp_isotig06284... at -/92.43%
3 1137nt, >cp_isotig02981... at -/93.84%
>Cluster 37
0 2835nt, >yl_JTQ_com670_c0_seq1... *
>Cluster 38
0 2275nt, >pb_iso00211... at +/93.93%
1 2647nt, >yl_JTQ_com323_c0_seq1... at +/91.39%


I want clusters with only 1 hit:

>Cluster 35
0 2856nt, >tru_clu8_1_inde2_or1... *
>Cluster 37
0 2835nt, >yl_JTQ_com670_c0_seq1... *


Then if possible output in this format:

>Cluster 35 tru_clu8_1_inde2_or1
>Cluster 37 yl_JTQ_com670_c0_seq1

Answer
$ awk 'NR>2{if(/^>/ && b ~ /^>/) print b"\n"a} {b=a ; a=$0}' infile.txt
>Cluster 35
0   2856nt, >tru_clu8_1_inde2_or1... *
>Cluster 37
0   2835nt, >yl_JTQ_com670_c0_seq1... *

Edit:

This will however not work if there is a final cluster with one hit. This workaround may work, also includes formatted output:

$ echo ">" >> infile.txt
$ awk 'NR>2{if(/^>/ && b ~ /^>/) {a=gensub(/^.*>(\w+).*/,"\\1", "g", a) ; print b,a} } {b=a ; a=$0}' infile.txt
>Cluster 35 tru_clu8_1_inde2_or1
>Cluster 37 yl_JTQ_com670_c0_seq1