What's the easiest way to match a character in a string
Hi, I wish to make an if statement matching a letter "D" in a string with no at most 3 characters:
Code:
$string="AHD" Ted |
Quote:
The instr function returns the position of the search string within the main string.. But, given that it returns zero if the substring is not present - then that will give the answer you want. So, in SHELL PROGRAMMING the easiest way I know - regardless of the length of the string is; Code:
string="AHD" So, for that reason - not elegance - it is the simplest and most readable IMHO. Dave |
Code:
if [[ $string = *D* ]] |
Or
Code:
if [[ $string =~ D ]] |
One more, just for fun:
Code:
if [[ ${string//[^D]} ]]; then Note that this is all assuming bash or similar shell. The OP didn't clearly state what language environment he's working in. Code:
$string="AHD" Edit in response to davemguru... You don't even need the test brackets. if checks the exit status of the final command run, so you can use grep alone: Code:
if grep -q "D" <<<"$string" ;then On systems without -q, use a redirection to dump the output away. |
In response to "David the H"
Yes, unfortunately I am showing my age. My solution was based on the lowest common denominator - viz: bourne shell. :) |
Yeah, I recognized your intent. I just commented because it's often good to give alternatives for different conditions, and to point out that test is not the only command you can use in most branching/looping constructs.
OTOH, I just noticed that you included the -s option in your command, which the gnu grep manpage states behaved like the -q option in some implementations. It also goes on to point out that if you truly need it to be portable, use redirection instead of either option. |
All times are GMT -5. The time now is 09:40 PM. |