Reputation: 691
I grep for a word/pattern in a file, if such a pattern doesn't exist in a file, then I want to print/echo "-". Can we do this on command line in a single lined command?
grep word <file> | <command to return "-" if "word" not present in file>
Similarly if script returns nothing , echo "-"
python script.py | <command to return "-" if script returns nothing/NULL
Upvotes: 0
Views: 2631
Reputation: 1650
If you want to check that there is no output for a command regardless of its returncode then you should check that there is no output, one way of doing that is:
awk '{print} END {if (NR == 0) print "-"}'
So for example:
$ grep - /dev/null | awk '{print} END {if (NR == 0) print "-"}'
-
$ echo some output | awk '{print} END {if (NR == 0) print "-"}'
some output
Upvotes: 1
Reputation: 171
This can be done by following command:
grep word file.txt || echo "-"
If word is present in file then it will print the line from file else will print -
.
If command is script then:
ret=`python script.py`; if [[ "$ret" ]];then echo "$ret"; else echo "-"; fi
Upvotes: 0