问题
Is there any way to find a position of a first character within a string in Bash under Mac OS X?
Something like:
stringZ=abcABC123ABCabc # 6
echo `expr index "$stringZ" C12` # C position.
as desribed in Advanced Bash-Scripting Guide
Couple of gotchas:
- The official index function
expr index $string $substring
is not present in OS X (BSD) match - Installing gnu match (gmatch) does not seem to be a portable solution in the realm of BSD systems
Any ideas?
回答1:
This is a horrible hack, and may not work for all cases.
tmp=${stringZ%%C12*} # Remove the search string and everything after it
echo $(( ${#tmp} + 1 )) # Add one to the length of the remaining prefix
回答2:
Might be an overkill but how about this:
$ echo 'abcABC123ABCabc' | awk 'match($0,"C"){print RSTART}'
6
来源:https://stackoverflow.com/questions/17615750/bash-find-position-of-character-in-a-string-under-os-x