Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash split string according to string

Tags:

bash

In python, I would do something simple like sRet = sOut.split('Word')

In bash, scrounged from other answers, I have the following two methods that are insufficient in my case, but may be useful to someone in the future:

sOut="I want this Point to matter"

1)  sRet=( $sOut )
2)  IFS="Point " read -r -a sRet <<< ${sOut}

echo ${sRet[-1]}

I want returned: "to matter"
(1) gives: "matter"
(2) gives: "er"

The first only splits by spaces, the second splits by the last character, in this case it would be 't'.

How do I split by a full string, as I would in python?

like image 455
Roman Avatar asked Nov 17 '25 05:11

Roman


1 Answers

sOut="I want this Point to matter"
s="Point "
[[ $sOut =~ $s(.*) ]] && echo ${BASH_REMATCH[1]}

Output:

to matter
like image 199
Cyrus Avatar answered Nov 18 '25 21:11

Cyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!