![如何(在 shell 脚本中)获取包含双引号的子字符串的位置?](https://linux22.com/image/187147/%E5%A6%82%E4%BD%95%EF%BC%88%E5%9C%A8%20shell%20%E8%84%9A%E6%9C%AC%E4%B8%AD%EF%BC%89%E8%8E%B7%E5%8F%96%E5%8C%85%E5%90%AB%E5%8F%8C%E5%BC%95%E5%8F%B7%E7%9A%84%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E4%BD%8D%E7%BD%AE%EF%BC%9F.png)
我有一个很长的字符串,我想找到第一次出现的子字符串 - 但子字符串包含双引号。我熟悉的唯一方法是:
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