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.

4

1 回答 1

0

首先,我不认为expr index你认为它会做

从它“工作”的系统:

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

来自man expr

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

注意“any”——即这个命令告诉你任何字母“l”、“o”、“g”、“i”、“c”第一次出现在字符串中的位置,我假设是不是你要找的

假设正确答案是 17,这是在纯 ksh93 中执行此操作的一种方法:

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

如果您的 ksh 太旧而无法使用.sh复合变量,您可以这样做:

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

即使在 ksh88 中也应该可以工作

于 2014-01-09T14:32:46.233 回答