Bash: Find character position in string under OS X

Is there a way to find the position of the first character in a string in Bash on Mac OS X?

Sort of:

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

as described in the Advanced Bash-Scripting Guide

A couple of fixes:

  • The official index function expr index $string $substring not present according to OS X (BSD)
  • Installing gnu compliance (gmatch) does not seem to be a portable BSD solution

Any ideas?

+3
source share
2 answers

This is a terrible 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 
+5
source

Maybe too much, but what about this:

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

Source: https://habr.com/ru/post/1491810/


All Articles