问题
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