Sed-用一个字符替换模式 - Sed - Replace a pattern with a single character

- 此内容更新于:2015-12-20
主题:

我很酷我有以下文本。我率10的10。使用sed我想改变我***的文本。我**10**10。我。e(取代)我试图使用模式但它取代了文本我************。我**********10*****10。

原文:

I have the following text

I am really cool. I rate myself 10 out of 10.

Using sed I want to change the text to

I * * *. I * * 10 * * 10.

i.e (Replace [a-z] to * ) I tried to use the pattern s/[a-z]/*/g

But it replaced the text as

I ** ****** ****. I **** ****** 10 *** ** 10.

解决方案:
你的模式取代每个小写字母明星。你想要尽可能多的连续小写字母替换为一个明星。重复使用:
原文:

Your pattern replaces each lower case letter with a star. You want to replace as many consecutive lower case letters with a star. Use + for repetition:

s/[a-z]\+/*/g
网友:没有工作。文本是一样的,没有改变。在windows上——使用cygwin。

(原文:Didn't work. The text is same - didn't change at all. - using cygwin on windows.)

网友:曾与s/[a-z]\+/*/g。但是有什么区别呢?

(原文:Worked with s/[a-z]\+/*/g . But what is the difference?)

楼主:@anupamD,不同的是,只有你不替换一个字符,但所有连续字符,匹配[a-z]。

(原文:@anupamD, the difference with just [a-z] is that you don't replace a single character but all consecutive characters, which match [a-z].)

网友:是的我是使用\+而不是+讨论,尽管你已经编辑它。谢谢顺便说一下。:)

(原文:yes actually i was talking about using \+ rather than +; although you already edited it. Thanks by the way. :))

楼主:@anupamD,将匹配字符+。会有重复的意义。很抱歉。

(原文:@anupamD, + will match the character +. \+ will have the meaning of repetition. Sorry about that.)

解决方案:
@ndn给出的答案是正确的想法,但默认SED使用Posix2基本正则表达式,所以你没有所有选项的完整的正则表达式。尤其是运营商(重复一次或更多)不是有效的对话。幸运的是,(重复零个或多个)。因此我们可以做:应该做你想做的事情。你还可以启用完整的正则表达式sed命令行选项(对我来说)
原文:

The answer given by @ndn is the right idea, but SED by default uses Posix 2 Basic Regular Expressions, so you don't have all of the options of full regular expressions. In particular the + operator (repeat once or more) isn't valid in SED. Fortunately the * (repeat zero or more) is. Thus we can do:

sed s/[a-z][a-z]*/*/g

Which should do what you want. You can also enable full regular expressions with a sed command line option (-r for me)

sed -r s/[a-z]+/*/g