How to add output “non_assigned” when there is no match in grep?

狂风中的少年 提交于 2020-11-29 11:06:49

问题


When I run a command (COMMAND) on one line of my input file (input.txt) I get an associated result where only one line is interesting, always starting by the world phylum.

For instance:

superkingdom    2759    Eukaryota
clade   554915  Amoebozoa
phylum  555280  Discosea
order   313555  Himatismenida
family  313556  Cochliopodiidae

So I run :

for p in $(cat input.txt) 
    do COMMAND $p | grep "\bphylum\b" >> results.txt
done

In order to have in my file result.txt all the lines like :

phylum  555280  Discosea

However there is sometimes no results with grep (there is no line starting with phylum), and it adds no line to results.txt. I would like for these specific cases add some line with "0" or "non assigned" for instance (so each line of input.txt matches results.txt).

clade   2696291 Ochrophyta
class   5747    Eustigmatophyceae
order   425074  Eustigmatales
family  425072  Monodopsidaceae

I have tried adding | awk print '{print $0"non_assigned"}' , unsuccesfully.

Do you have any ideas to help me ? A member advices me to use awk '/phylum/{print $0}!/phylum/{print "non_assigned";exit} but i get as output "non_assigned" even if the phylum result is present.


回答1:


This will do the job:

for p in $(<input.txt)
do
    (COMMAND $p | grep -w "phylum") || echo "non_assigned"
done >> results.txt

This runs the command and the grep in a subshell. If the grep finds 'phylum', the RHS of the || is not run; if 'phylum' is not found, the echo is executed to output a suitable marker.

Notice that the redirection has been moved to after the done; it might be better to use > rather than >> now.

Beware the set option -o pipefail — if the command can fail, you might need to use set +o pipefail. However, it is disabled by default, so you'll probably be OK.



来源:https://stackoverflow.com/questions/64454736/how-to-add-output-non-assigned-when-there-is-no-match-in-grep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!