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

标签 macos bash indexing match

有什么方法可以在 Mac OS X 下的 Bash 中找到字符串中第一个字符的位置?

类似于:

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

Advanced Bash-Scripting Guide 中所述

几个问题:

  1. 官方的 index 函数 expr index $string $substring 不是 存在于 OS X (BSD) 匹配
  2. 安装 gnu match (gmatch) 似乎不是一个 BSD 系统领域的可移植解决方案

有什么想法吗?

最佳答案

这是一个可怕的 hack,可能不适用于所有情况。

tmp=${stringZ%%C12*}     # Remove the search string and everything after it
echo $(( ${#tmp} + 1 )) # Add one to the length of the remaining prefix

关于macos - Bash:在 OS X 下的字符串中查找字符的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17615750/

相关文章:

java - 如何在 Mac 中永久设置 JAVA_HOME?

javascript - Node 和错误 : EMFILE, 打开的文件太多

bash - 在 osx 终端上为所有用户添加别名

java - 搜索对象数组和索引位置

python - PySide2 - 调用 QFileSystemModel.index() 时程序崩溃

python - 通过重复数组索引对数组值求和

objective-c - 在 Swift/Objective-C 中监听窗口调整大小事件

bash - 使用 scala.sys.process 执行 bash 字符串

bash - bash中的-f是什么意思

macos - 核心数据崩溃报告: sqlite3VdbeHalt in loading array controller