简体   繁体   中英

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?

Pure bash:

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

You could use an array:

string="xyz walked his dog abc"

a=( $string )

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

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]}"

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/}" a="xyz walked his dog abc"; echo "${a/walked his dog/}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM