I have a co-worker that is trying to make a Wheel of Fortune game and he wants to know if there is a way to search a string for the letter given by the user.
echo "string" | grep 'x' >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "Found x in string"
else
echo "Couldnt find it"
fi
You get the idea....
Check out my hangman shell script - you can see the technique employed.
I wish I had a job like your co-worker! ![]()
Cheers
ZB
Thanks for the help.
Zazzybob,
I had the same probelm as turbulence's co-worker...and ur solution really worked.. but can u please explain the idea behind ur solution?
i didnt get what is the significance of /dev/null there in the code?
thanks
sirisha
Grep, in its simplest form, has this habit of shouting out loud, about the things it discovered. And if it did find, then the exit status is 0. Else 1.
In the OP's case, he wants only detect the presence of a letter in a string. So whatever grep outputs, be it success or failure, discard it.
Here is a non-grep solution as well
[~/temp]$ echo $LANG
en_US.UTF-8
[~/temp]$ [[ "$LANG" == *US* ]] && echo "US LANG" || echo "LOCALE"
US LANG
[~/temp]$
vino,
i am afraid if i understand what u suggested. Your explantion of how grep works and thereby comparing the exit status of grep to detect the presence of a letter in the string is understood, but i didnt quite follow two aspects:
- why is there a /dev/null in his piece of code?
- How are achieving the same without a grep in your solution?
can you please take efforts to elaborate?
Thanks a ton again,
Sirisha
I did mention that if grep finds anything, it will output whatever it found. Together with that, the exit status will be set accordingly.
See this
[/tmp]$ cat xyz
maroon
pink
yellow
[/tmp]$ grep pink xyz
pink
[/tmp]$ echo $?
0
[/tmp]$ grep pink xyz 1> /dev/null
[/tmp]$ echo $?
0
[/tmp]$ grep pink xyz.file 1> /dev/null
grep: xyz.file: No such file or directory
[/tmp]$ echo $?
2
[/tmp]$ grep pink xyz.file 1> /dev/null 2> /dev/null
[/tmp]$ echo $?
2
[/tmp]$ grep pink xyz 1> /dev/null 2> /dev/null
[/tmp]$ echo $?
0
[/tmp]$
That should explain the role of /dev/null. If not, read it from up the wiki site.
The non-grep solution makes use of a shell-builtin.
See this thread - String extraction from user input - sh
vino
Thanks so much Vino! Now that's pretty much clear.