1

I am trying to get the index of a particular substring from a string in KornShell (ksh), but all I get is syntax error. The Below is the syntax I am using

trying to get the index of "logic" from string "filename_newpart_logic"

command used is expr index "$string1" "logic"

but the result is expr: syntax error

I have tried the same in some online command editors and it works perfectly, but not in the shell. The ksh version is quite old. Please let me know if there is any other syntax/alternative way to achieve this.

javaPlease42
  • 4,699
  • 7
  • 36
  • 65
  • possible duplicate of [Position of a string within a string using Linux shell script?](http://stackoverflow.com/questions/5031764/position-of-a-string-within-a-string-using-linux-shell-script) – Marco Baldelli Oct 02 '13 at 18:25
  • 2
    `expr` is an external command, independent of your shell. Your version of `expr` does not appear to support the 'index' command, as is true (for example) of the version that ships with Mac OS X. – chepner Oct 02 '13 at 18:47

1 Answers1

0

first of all, i don't think expr index does what you think it does

from a system where it "works":

> string1=filename_newpart_logic
> expr index "$string1" logic
2
>

from man expr:

       index STRING CHARS
              index in STRING where any CHARS is found, or 0

note the "any" -- i.e. this command is telling you where the first occurrence of any of the letters "l", "o", "g", "i", "c" is in the string, which i assume is not what you're looking for

assuming the correct answer is 17, here's one way to do it in pure ksh93:

> : ${string1/logic*};print $((${#string1}-${#.sh.match}))
17
>

if your ksh is too old to have the .sh compound variable, you could do this:

> t=${string1%%logic*};print ${#t}
17
>

which should work even in ksh88

Aaron Davies
  • 1,190
  • 1
  • 11
  • 17