string 来自第一个 indexof 子字符串的 Shell 脚本子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10349102/
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
Shell script substring from first indexof substring
提问by pathikrit
I want to accomplish the equivalent of the following pseudo-code in bash (both a and b are inputs to my script) :
我想在 bash 中完成以下伪代码的等效操作(a 和 b 都是我的脚本的输入):
String a = "some long string";
String b = "ri";
print (a.substring(a.firstIndexOf(b), a.length()); //prints 'ring'
How can I do this in shell script?
我怎样才能在shell脚本中做到这一点?
采纳答案by codaddict
You can do:
你可以做:
$ a="some long string"
$ b="ri"
$ echo $a | grep -o "$b.*"
ring
回答by Josshad
Try:
尝试:
$ a="some long string"
$ b="ri"
$ echo ${a/*$b/$b}
ring
$ echo ${a/$b*/$b}
some long stri
回答by lessyv
grep
, sed
and so on can be used but it is not pure-bash.
grep
,sed
等等都可以使用,但它不是纯 bash。
expr
is a good choice but index
parameter is not, because it matches character not the whole string, try with a = "some wrong string"
it matches the first r
.
expr
是一个不错的选择,但index
参数不是,因为它匹配字符而不是整个字符串,请尝试使用a = "some wrong string"
它匹配第一个r
.
Instead use expr match
with its regular expression parameter :
而是expr match
与其正则表达式参数一起使用:
a="some long string";
b="ri";
echo ${a:$(expr match "$a" ".*${b}") - $(expr length "$b")}
It also works with a = "some wrong string"
它也适用于 a = "some wrong string"
回答by Fritz G. Mehner
Try this:
尝试这个:
a="some long string"
b="ri"
echo ${b}${a#*${b}}