Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Macos Bash:在OSX下查找字符串中字符的位置_Macos_Bash_Indexing_Match - Fatal编程技术网

Macos Bash:在OSX下查找字符串中字符的位置

Macos Bash:在OSX下查找字符串中字符的位置,macos,bash,indexing,match,Macos,Bash,Indexing,Match,在Mac OS X下,有没有办法在Bash中找到字符串中第一个字符的位置 比如: stringZ=abcABC123ABCabc # 6 echo `expr index "$stringZ" C12` # C position. 如文中所述 两个陷阱: 官方索引函数expr index$string$substring不可用 存在于OS X(BSD)匹配中 安装gnu match(gmatch)似乎不是一个好办法 BSD系统领

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

比如:

stringZ=abcABC123ABCabc                      # 6
echo `expr index "$stringZ" C12`             # C position.
如文中所述

两个陷阱:

  • 官方索引函数
    expr index$string$substring
    不可用 存在于OS X(BSD)匹配中
  • 安装gnu match(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
    

    可能有点过火,但这样如何:

    $ echo 'abcABC123ABCabc' | awk 'match($0,"C"){print RSTART}'
    6
    

    我没有要测试的OSX,但是
    echo$stringZ | grep C12-o-b
    可以做到吗?$echo“ASDfsfssdf”| grep D-o-b 0:D您可以不使用-o进行测试吗?在我的bash版本中,在Linux上,-b的行为被-o改变,但是从MacOSX手册页上看到,
    grepc12-b
    可能会工作。
    echo“ASDfsfssdf”| grepd0:ASDfsfssdf
    我只是想提出同样的建议
    %%
    应找到第一个匹配项。
    %%
    将删除最长的匹配项;两者都将从第一次出现开始。双倍的百分比似乎是最好的选择。例如,尝试以下操作:
    stringZ=“A B=C=D=F”tmp=${stringZ%%=*}删除搜索字符串及其后的所有内容echo$(${A B=C}+1))。#在剩余前缀的长度中添加一个
    ,而单个百分比的工作方式如下:
    +stringZ='A B=C=D=F'+tmp='A B=D'+echo 8
    (查找搜索字符串的索引),使用的模式将始终以
    *
    结尾,在这种情况下
    %
    %
    之间没有区别。