我有一个很长的字符串,我想找到第一次出现的子字符串 - 但子字符串包含双引号。我熟悉的唯一方法是:
mystr='a very, very, extremely, incredibly long string of text that contains the phrase he said, "Hello!" somewhere in the middle'
strpos=`expr index "$mystr" Hello`
echo $strpos
它返回 92。但是如果子字符串包含双引号,那么这将不起作用......
strpos=`expr index "$mystr" he said, "Hello`
我尝试转义双引号(和空格)。我尝试用单引号将字符串括起来以查找。如果我设法运行它而没有收到“意外的 EOF”或“语法错误”,它会返回一个荒谬的结果,如“2”。 (这个职位有数千个。)我猜我无法做我想做的事expr index
但如果不能,那么怎么办能我做吗?
答案1
我认为它会在第一个字符串中搜索第二个字符串的字符。您可以使用 grep
mystr='a very, very, extremely, incredibly long string of text that contains 2 the phrase he said, "Hello!" somewhere in the middle'
echo "$mystr"| grep -o -b Hello!
它会回来的91:Hello!
。这里索引从0开始。
如果像 a 这样的情况多次出现,则输出将为
0:a 58:a 65:a 77:a 85:a
如果你也想搜索双引号,那么就转义它们,
echo "$mystr"| grep -o -b \"Hello!\"
输出将是
90:"Hello!"
答案2
仅使用参数扩展:
mystr='a very, very, extremely, incredibly long string of text that contains the phrase he said, "Hello!" somewhere in the middle'
searchstr='"Hello!"'
newstr="${mystr%%$searchstr*}"
echo "position = $((${#newstr} + 1))"
答案3
让我们看看这是否是您正在寻找的:
mystr='a very, very, extremely, incredibly long string of text that contains the phrase he said, "Hello!" somewhere in the middle'
$ var=$(echo "$mystr" | grep -o -b "Hello!" | head -1)
$ echo "$var"
91:Hello!
$ pos="${var%:*}"
$ echo "$pos"
91