How to select element with specific string with awk

Viewed 38

There is the example with two lines as below, but the real data have many lines. I want to only pick the taxa ending with 'viridae' in linux, maybe with awk. The order number of this kind of string/word is different if splitting by ";", like Orthomyxoviridae as 8th, and Solemoviridae as 7th.

Viruses; Riboviria; Orthornavirae; Negarnaviricota; Polyploviricotina; Insthoviricetes; Articulavirales; Orthomyxoviridae; Alphainfluenzavirus

Viruses; Riboviria; Orthornavirae; Pisuviricota; Pisoniviricetes; Sobelivirales; Solemoviridae; Polerovirus

May I ask how to achieve it? Thanks

2 Answers

Try this:

awk -F';' '{for(i=1;i<=NF;i++) if($i~"viridae") print $i}' file

And if you want to strip the leading or training spaces:

awk -F '[ \t]*;[ \t]*' '{for(i=1;i<=NF;i++) if($i~"viridae") print $i}' file

Question: if no match, how to add one NA to this row?

awk -F '[ \t]*;[ \t]*' '{
    f=0
    for(i=1;i<=NF;i++) if($i~"viridae$") {f=1; print $i}
    if (!f) print "N/A"
}' file

Why awk? This is what grep has been written for :-)

I have created following file:

Prompt> cat test.txt
first latest nogeentest testament blabla
toet toet

I want to see all words, ending with the word "test":

Prompt> grep -o "[a-z]*[a-z]test" test.txt
latest
nogeentest

I want to see all words, containing the word "test":

Prompt> grep -o "[a-z]*test[a-z]*" test.txt
latest
nogeentest
testament

You might be helped with:

Prompt> grep -o "[a-z]*[a-z]viridae" test.txt

Have fun!

For your information: [a-z]*[a-z] means "any number of letters, followed by any letter", which can sometimes be replaced by [a-z]+. However, on my system this does not seem to work.

Related