你需要使用grep
吗?这是一个sed
示例,以防万一:
$ echo "john's apostrophe is a 'challenge'" | sed -re "s/'(\S*)'/\1/g"
john's apostrophe is a challenge
sed
是一个流编辑器,我用它来执行替换(格式是s/pattern/subst/
,g
代表全局。我匹配任意数量(*
)的非空白字符(\S
)并将其替换为同一组字符,指代它作为\1
(我用圆括号捕获它(...)
。
编辑:好的,这是一个丑陋的类似 Perl 的grep
例子:
$ echo "john's apostrophe is a 'challenge'" | grep -oP "(?<=')\S*(?=')|\w+'?\w*"
john's
apostrophe
is
a
challenge
我不知道我做了什么,所以很可能出现意外行为:)
grep
我使用肯定的环视断言来匹配单引号中的单词(断言用于引号不是匹配的一部分)或(|
)带有可选撇号的单词,用“一个或多个单词”表示字符” ( \w+
) 后跟'
(或不),然后是可选的一些单词字符。
更多编辑:这是一个sed
似乎可以完成这项工作并处理@tchrist的示例的命令:
$ echo "john's apostrophe is a 'challenge'" | sed -re "s/(\W|^) '(\w*)'(\W|$)/\1\2\3/g"
john's apostrophe is a challenge
$ echo "’Tis especially hard, ’tisn’t it now, to leave it for the dogs’ breakfast, let a lone for the cats'" | sed -re "s/(\W|^)'(\w*)'(\W|$)/\1\2\3/g"
’Tis especially hard, ’tisn’t it now, to leave it for the dogs’ breakfast, let a lone for the cats'