Bash:在 OS X 下查找字符串中字符的位置

2024-03-04

有没有办法找到字符串中第一个字符的位置Bash under Mac OS X?

就像是:

stringZ=abcABC123ABCabc                      # 6
echo `expr index "$stringZ" C12`             # C position.

如中所述高级 Bash 脚本指南 http://tldp.org/LDP/abs/html/string-manipulation.html

几个陷阱:

  1. 官方index功能expr index $string $substring不是 存在于 OS X (BSD) 中match
  2. 安装 gnu 匹配 (gmatch)似乎不是 BSD 系统领域的便携式解决方案

有任何想法吗?


这是一个可怕的黑客行为,可能不适用于所有情况。

tmp=${stringZ%%C12*}     # Remove the search string and everything after it
echo $(( ${#tmp} + 1 )) # Add one to the length of the remaining prefix
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Bash:在 OS X 下查找字符串中字符的位置 的相关文章

随机推荐