1

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

4

4 回答 4

2

纯重击:

var="xyz walked his dog abc"
echo ${var/walked*dog/}
xyz  abc
于 2013-05-23T18:22:21.440 回答
1

你可以使用一个数组:

string="xyz walked his dog abc"

a=( $string )

result="${a[0]} ${a[-1]}"
于 2013-05-23T18:15:46.113 回答
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]}"
于 2013-05-23T18:29:55.307 回答
0

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

于 2013-05-23T18:17:56.357 回答