正则表达式用已知的第一个和最后一个单词替换子字符串

时间:2013-05-23 18:09:14

标签: regex bash

我有一个字符串"xyz walked his dog abc"。我想删除子字符串"walked his dog",只有"xyz abc"。我怎么能在bash正则表达式中这样做?

4 个答案:

答案 0 :(得分:2)

Pure bash:

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

答案 1 :(得分:1)

您可以使用数组:

string="xyz walked his dog abc"

a=( $string )

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

答案 2 :(得分:1)

虽然正则表达式对于此特定操作来说是过度的(我建议ravoori's answer),但如果需要更改,最好知道语法:

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

答案 3 :(得分:0)

最简单的方法可能是使用sedsed -r 's/walked his dog//'(用空字符串替换子字符串)。或者使用内置替换机制(不支持正则表达式):a="xyz walked his dog abc"; echo "${a/walked his dog/}"