Bash:在 OS X 下查找字符串中字符的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17615750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: Find position of character in a string under OS X
提问by Ivan Balashov
Is there any way to find a position of a first character within a string in Bashunder Mac OS X?
有没有办法在Mac OS X下的Bash 中找到字符串中第一个字符的位置?
Something like:
就像是:
stringZ=abcABC123ABCabc # 6
echo `expr index "$stringZ" C12` # C position.
as desribed in Advanced Bash-Scripting Guide
Couple of gotchas:
几个问题:
- The official indexfunction
expr index $string $substringis 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
- OS X (BSD) match 中不存在官方索引功能
expr index $string $substring - 安装 gnu match ( gmatch) 在 BSD 系统领域似乎不是一个可移植的解决方案
Any ideas?
有任何想法吗?
回答by chepner
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
回答by jaypal singh
Might be an overkill but how about this:
可能有点矫枉过正,但是这个怎么样:
$ echo 'abcABC123ABCabc' | awk 'match(##代码##,"C"){print RSTART}'
6

