在vim中搜索并替换选定的文件路径 [英] Search and replace the selected filepath in vim

查看:54
本文介绍了在vim中搜索并替换选定的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常处理里面充满文件路径的文件.我希望能够在可视模式下快速选择我的文件路径并将其替换为其他一些文件路径.

I often work with files full of filepaths inside. I want to be able to quickly select my filepath in Visual Mode and replace it with some other filepath.

例如我有这样的文件:

balvadsd /mnt/Windows/Documents\ and\ Settings/stuff/file.exe blablabalba albla
/mnt/Windows/Documents\ and\ Settings/stuff/file.exe bla2 vslva 21 
stuff foo bar dsad /mnt/Windows/Documents\ and\ Settings/stuff/file.exe 

我需要

  1. 搜索所有出现的 /mnt/Windows/Documents\ and\ Settings/stuff/file.exe
  2. 用其他路径替换我的路径 /mnt/Windows/Documents\ and\ Settings/stuff/file.exe.棘手的是像这个 由于斜线、反斜线和点,不能使用文件路径.
  1. search for all occurrences of /mnt/Windows/Documents\ and\ Settings/stuff/file.exe
  2. replace my path /mnt/Windows/Documents\ and\ Settings/stuff/file.exe with some other path. The tricky bit is that the solutions like this one don't work with filepaths because of slashes, backslashes and dots.

推荐答案

您可以使用 \ 对正则表达式元字符进行转义.所以 foo/bar 成为你的正则表达式的 foo\/bar .或者您可以使用不同的分隔符,例如 #.但是你仍然需要转义 ..您可以通过使用 \V 来避免转义 . 和其他正则表达式元字符的需要.使用 \V 意味着现在必须转义所有正则表达式元字符,这意味着未转义的章程与其文字本身匹配.

You can escape the regex metacharacters with \. So foo/bar becomes foo\/bar for your regex. Or you can use a different seperator like #. However you still need escape the .. You can avoid the need to escape . and other regex metacharacters by using \V for very nomagic. Using \V means all regex metacharacters now must be escaped meaning non escaped charters match their literal selves.

:%s#\V/mnt/Windows/Documents\ and\ Settings/stuff/file.exe#replacement#g

然而,所有这些逃避都会变得烦人.我通常使用视觉星图和/或 插件.这意味着我在视觉上选择了文本,然后按 *.然后你可以做 :%s//replacement/:%s##replacement# 来进行替换.

However all that escaping can become annoying. I usually use a visual star mapping and/or plugin. Meaning I visually select the text then press *. Then you can just do :%s//replacement/ or :%s##replacement# to make the replacement.

Neil Drew 有一些不错的 Vimcast 剧集谈到了这个:

There are some nice Vimcast episodes by Neil Drew that talk about this:

您可以使用 gn 动作和 . 命令进一步扩展这个想法.请参阅以下 vimcast 片段:使用 gn 操作搜索匹配.

You can take this idea further with the gn motion and the . command. See the following vimcast episode: Operating on search matches using gn.

有关更多帮助,请参阅:

For more help see:

:h /\V
:h gn

这篇关于在vim中搜索并替换选定的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆