如何添加输出“non_assigned"当 grep 中没有匹配项时? [英] How to add output "non_assigned" when there is no match in grep?

查看:19
本文介绍了如何添加输出“non_assigned"当 grep 中没有匹配项时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在输入文件 (input.txt) 的一行上运行命令 (COMMAND) 时,我得到一个相关的结果,其中只有一行是有趣的,总是从世界门开始.

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.

例如:

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

所以我运行:

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

为了在我的文件 result.txt 中包含以下所有行:

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

phylum  555280  Discosea

然而,有时grep 没有结果(没有以phylum 开头的行),并且它没有向results.txt 添加任何行.我想为这些特定情况添加一些带有0"的行或未分配"例如(所以 input.txt 的每一行都匹配 results.txt).

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

我尝试添加 |awk 打印 '{print $0"non_assigned"}' ,不成功.

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

你有什么想法可以帮助我吗?一位成员建议我使用 awk '/phylum/{print $0}!/phylum/{print "non_assigned";exit} 但我得到的输出是 "non_assigned"即使存在门结果.

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.

推荐答案

这将完成工作:

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

这会在子 shell 中运行命令和 grep.如果grep 找到'phylum',则不运行|| 的RHS;如果没有找到 'phylum',则执行 echo 以输出合适的标记.

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.

注意重定向已经移到done之后;现在使用 > 而不是 >> 可能更好.

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

当心 set 选项 -o pipefail — 如果命令可能失败,您可能需要使用 set +o pipefail.但是,默认情况下它是禁用的,因此您可能会没事.

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.

这篇关于如何添加输出“non_assigned"当 grep 中没有匹配项时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆