Budhapest
Budhapest

Reputation: 601

Regex replace substring with known first and last word

I have a string say "xyz walked his dog abc". And I want to remove the substring "walked his dog" and just have "xyz abc". How can I do so in bash regex?

Upvotes: 1

Views: 559

Answers (4)

chepner
chepner

Reputation: 531075

While a regular expression is overkill for this particular operation (I recommend ravoori's answer), it's good to know the syntax if needs change:

# Two capture groups, one preceding the string to remove, the other following it
regex='(.*)walked his dog(.*)'
[[ $string =~ $regex ]]
# Elements 1 through n of BASH_REMATCH correspond to the 1st through nth capture
# groups. (Element 0 is the string matched by the entire regex)
string="${BASH_REMATCH[1]}${BASH_REMATCH[2]}"

Upvotes: 2

iruvar
iruvar

Reputation: 23364

Pure bash:

var="xyz walked his dog abc"
echo ${var/walked*dog/}
xyz  abc

Upvotes: 1

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

Easiest way is probably using sed: sed -r 's/walked his dog//' (replace a substring with the empty string). Or using the built-in replacement mechanism (no regex support, though): a="xyz walked his dog abc"; echo "${a/walked his dog/}"

Upvotes: 0

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

You could use an array:

string="xyz walked his dog abc"

a=( $string )

result="${a[0]} ${a[-1]}"

Upvotes: 0

Related Questions