字符串在使用 Linux shell 脚本的字符串中的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5031764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:22:00  来源:igfitidea点击:

Position of a string within a string using Linux shell script?

linuxshell

提问by Yazz.com

If I have the text in a shell variable, say $a:

如果我在 shell 变量中有文本,请说$a

a="The cat sat on the mat"

How can I search for "cat" and return 4 using a Linux shell script, or -1 if not found?

如何使用 Linux shell 脚本搜索“cat”并返回 4,如果未找到则返回 -1?

回答by qbert220

echo $a | grep -bo cat | sed 's/:.*$//'

回答by Nikita Rybak

I used awkfor this

我为此使用了awk

a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'

回答by Cercerilla

You can use grep to get the byte-offset of the matching part of a string:

您可以使用 grep 获取字符串匹配部分的字节偏移量:

echo $str | grep -b -o str

As per your example:

根据您的示例:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

you can pipe that to awk if you just want the first part

如果你只想要第一部分,你可以将它传递给 awk

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print }'

回答by glenn Hymanman

With bash

用 bash

a="The cat sat on the mat"
b=cat
strindex() { 
  x="${1%%*}"
  [[ "$x" = "" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1