Shell script substring from first indexof substring
Solution 1
You can do:
$ a="some long string"
$ b="ri"
$ echo $a | grep -o "$b.*"
ring
Solution 2
Try:
$ a="some long string"
$ b="ri"
$ echo ${a/*$b/$b}
ring
$ echo ${a/$b*/$b}
some long stri
Solution 3
Try this:
a="some long string"
b="ri"
echo ${b}${a#*${b}}
Solution 4
grep
, sed
and so on can be used but it is not pure-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
.
Instead use expr match
with its regular expression parameter :
a="some long string";
b="ri";
echo ${a:$(expr match "$a" ".*${b}") - $(expr length "$b")}
It also works with a = "some wrong string"
pathikrit
Experienced in developing scalable solutions for complex problems. I enjoy working full-stack - from architecting schema and data-flows, implementing algorithms, designing APIs to crafting innovative UIs. My professional interests include algorithms, functional programming, finance, data analytics and visualization.
Updated on January 01, 2020Comments
-
pathikrit over 4 years
I want to accomplish the equivalent of the following pseudo-code in bash (both a and b are inputs to my script) :
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?
-
Idemax over 6 yearsnot index of but the string itself and pops error if not find
-
tripleee over 6 yearsClever. You should double-quote the argument to
echo
, though. -
Gudlaugur Egilsson about 2 yearsThis is a greedy match, so if there is a second "ri", this prints until and from the second match, not the first.