Bash: Find position of character in a string under OS X

China☆狼群 提交于 2021-01-27 14:00:31

问题


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:

  1. The official index function expr index $string $substring is not present in OS X (BSD) match
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!