Shell script substring from first indexof substring

45,705

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"

Share:
45,705
pathikrit
Author by

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, 2020

Comments

  • pathikrit
    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
    Idemax over 6 years
    not index of but the string itself and pops error if not find
  • tripleee
    tripleee over 6 years
    Clever. You should double-quote the argument to echo, though.
  • Gudlaugur Egilsson
    Gudlaugur Egilsson about 2 years
    This is a greedy match, so if there is a second "ri", this prints until and from the second match, not the first.