grep 'Marcus' list.txt | awk '{print $2}'
list.txt
Mary 10
John 20
How do i write if grep nothing then return zero instead of display nothing in the line.
grep 'Marcus' list.txt | awk '{print $2}'
list.txt
Mary 10
John 20
How do i write if grep nothing then return zero instead of display nothing in the line.
I don't know how to display a certain string when the grep did not find a match. But the code below will output zero (instead of nothing) if there is no match.
grep -c "Marcus" list.txt
grep -c "Marcus" list.txt | awk '{print $2}'
it displays nothing.
What i want is
if i cant grep the keyword then
display zero
else
display the value
in a single line of code.
Don't put the awk part. Just the grep.
[******@******** home]$ grep -c "Marcus" 1.txt
0
i want grep the value based on the name. If the name does not exist in the file return 0 ( mean grep nothing).
It can be cut or awk command..
[[ -n `grep 'marcus' list.txt` ]]&& echo `grep 'marcus' list.txt|cut -d" " -f2`|| echo 0
Do you want the script in the command line or inside a program?
Yes, i need to write in the shell script.
---------- Post updated at 02:22 PM ---------- Previous update was at 02:21 PM ----------
The code you provided is unable to get the answer when i type in the keyword which existed in the list, it still return 0.
adm/alvin% [[ -n `grep 'john' list.txt` ]]&& echo `grep 'john' list.txt|cut -d" " -f2`|| echo 0
Missing ]
0
Program:
$1 can be Marcus or any input you want to find in the file
grep -c $1 1.txt
if [ $? -ne "0" ]
then
echo "0"
fi
is it posible to make it ternary if else?
Three separate if..else statements? Or, nested if statement? Can you please expound.
Something like this
(if exist)? echo the value : echo 0
grep -c $1 1.txt
if [ $? -ne "0" ]
then
echo "0"
else
echo $1
fi
grep 'Marcus' list.txt | awk '{print $2}; END { if (!found) print "0" }'
It returns "0" but it also returns "0" on other names that are not Mary, when you search for Mary. Is that what you wanted?
Sir, whatever the input will be, the code will output the "0".
in my list.txt contain
------------------
Mary 10
John 20
So, if i the name is not in the list like 'Marcus', it will return 0.
if the name exist in the list like 'John', it will return 20.
This is what i want, you are almost got it.
grep 'Marcus' list.txt | awk '{print $2}; END { if (!found) print "0" }'
found): Event not found
Why cannot run?
---------- Post updated at 03:21 PM ---------- Previous update was at 03:08 PM ----------
Yes, you are right.
% grep 'john' list.txt | awk '{print $2}END{ if (! found) print "0" }'
20
0
is it possible to add in else ?
295 % grep 'John' filename| awk '{print $2}END{ if (! found) {print "0"} else {print "20"} }'
20
0
Why got two value display?
Try this sir.
#!/bin/sh
STR=`grep $1 1.txt | awk '{ print $2 }'`
if [ -z $STR ]
then
echo "0"
else
echo $STR
fi
Are you even sure what you are trying to achieve ?