Sed regexp 寻找空白或行尾 [英] Sed regexp looking for either whitespace or end of line
问题描述
我正在尝试检测包含三个部分的模式:
I'm trying to detect a pattern that has three parts:
- 一个空格
- m"或t"
- 空格或行尾
我想保留#2 和#3.例如,我想将 我确定他没有" 更改为 我确定他没有"
I want to keep #2 and #3. For example, I'd like to change "i m sure he doesn t" to "im sure he doesnt"
我在表达 #3 时遇到问题,因为 [ $]
似乎只匹配空格,而不是行尾.这是我尝试过的:
I'm having trouble expressing #3, since [ $]
only seems to match spaces, not line-ends. Here's what I've tried:
$ echo "i m sure he doesn t" | sed 's/ \([mt]\)\([ $]\)/\1\2/g'
im sure he doesn t
我应该如何在上面的表达式中表达空格或行尾"?谢谢!
How should I express "either a space or end of line" in the expression above? Thanks!
推荐答案
只匹配空格,然后是 m 或 t,然后空格或换行符不会捕获带有标点符号的情况,例如"please don t!"
中缺少 '
.一个更通用的解决方案是改用词边界:
Just matching space, then m or t, then space or newline won't catch cases with punctuation, e.g. a missing '
in "please don t!"
. A more general solution is to use word boundaries instead:
echo "i m sure he doesn t test test don t." | sed 's/ \([mt]\)[[:>:]]/\1/g'
时髦的 [[:>:]]
在 OS X(我使用)上是必需的,请参阅 Larry Gerndt 对 sed 全词搜索和替换.在其他 sed 版本上,您可以使用 \b
(任何单词边界)或 \>
代替.
The funky [[:>:]]
is required on OS X (which I use), see Larry Gerndt's answer to sed whole word search and replace. On other sed flavors you may be able to use \b
(any word boundary) or \>
instead.
# example with word boundary
echo "i m sure he doesn t test test don t." | sed 's/ \([mt]\)[[:>:]]/\1/g'
im sure he doesnt test test dont.
这篇关于Sed regexp 寻找空白或行尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!