vim替换模式

时间:2010-08-06 09:23:22

标签: vim

  <created>
    pat@c.com 
  </created>

我想替换上面的内容,但用户名可能会有所不同,即pat @ c.com,harry @ c.com ......

      <created>
       tom@c.com
     </created>

在vim中替换它的命令是什么

       %s/<created>\r*\r</created>/new string

1 个答案:

答案 0 :(得分:5)

这取决于您想要的格式,但对于您引用的特定示例,您可以执行以下操作之一:

非常简单,没有上下文:用tom@c.com替换pat@c.com

:%s/pat@c\.com/tom@c.com/g

使用上下文

:%s:<created>\s*\n\s*\zs.\{-}\ze@c\.com\s*\n\s*</created>:tom

作为解释:

:%s:XXX:YYY - Substitute XXX with YYY over the whole file (using colons as delimiters to avoid having to escape slashes or @s with a backslash)

where XXX is:
<created> - literal text to search for
\s*       - soak up any spaces or tabs to the end of the line
\n        - a new line character
\s*       - soak up any spaces or tabs at the start of the line
\zs       - special code that says "the match starts here", so only the bit between this and the \ze are actually replaced
.\{-}     - catch any characters, as few as possible - this will match 'pat' in the example above
\ze       - end of the bit we're changing
@c        - literal text - the @ and the start of the domain name
\.        - '.' means any character, so to match a literal dot, you must escape it
com       - literal text - the end of the email address
\s*       - any spaces/tabs to the end of the line
\n        - a new line character
\s*       - any spaces/tabs
</created> - literal match on the terminator (works because we don't use '/' as the delimiters)

and YYY is just the literal string "tom" to insert

另一种形式:

:%s:<created>\_s*\zs\S\+\ze\_s*</created>:tom@c.com

:%s:XXX:YYY: - as before

where XXX is:

<created>  - literal text to search for
\_s*       - search for zero or more white-space characters, including new-lines (hence the underscore)
\zs        - as before, this is the start of the bit we want to replace (so we're not changing the <created> bit)
\S\+       - one or more non-whitespace characters (\+ is one or more, * is zero or more) - this should catch the whole email address
\ze        - as before, the end of the match
\_s*       - zero or more white-space characters
</created> - the end delimiter

YYY is then the whole email address.

我希望能为您提供一些有用的信息。网上有很多关于正则表达式的有用参考指南(这些都是这些)(尽管注意到Vim使用的格式与大多数格式略有不同:\+而不是+等。我强烈建议阅读:

:help pattern.txt

但要记住那里有很多东西,所以请逐渐阅读并进行实验。您也可以先使用简单搜索(按/)并考虑稍后进行替换,例如类型:

/<created>\_s*\zs\S\+\ze\_s*<\/created>

请注意,我在/前面添加了反斜杠,因为搜索起点为/。一个聪明的诀窍是:s默认情况下使用最后一次搜索,因此您可以键入上面的行(/<created>\_s*\zs\S\+\ze\_s*<\/created>)并调整它直到它是正确的,然后只做:%s::tom@c.com从那以后上面标有XXX的位不存在,它将使用您的上次搜索并正常工作!

如果上面有任何位,你不明白,:help是你的朋友。例如,要了解\zs,请输入:

:help \zs

有关\_s的信息,请输入:

:help \_s

有关:s类型的一般信息:

:help :s

等...