首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Vim搜索和替换所选文本

Vim搜索和替换所选文本
EN

Stack Overflow用户
提问于 2009-03-24 09:02:21
回答 12查看 70.9K关注 0票数 128

假设我们有一个文本,我进入可视模式并选择了一些文本。如何快速搜索突出显示的文本并将其替换为其他内容?

EN

回答 12

Stack Overflow用户

发布于 2013-04-11 03:39:18

这种快速而简单的映射搜索视觉上突出显示的文本(不覆盖h寄存器),并且不使用终端相关+寄存器:

代码语言:javascript
复制
" search for visually hightlighted text
vnoremap <c-f> y<ESC>/<c-r>"<CR>   

如果您不喜欢ctrl-f,请将其更改为您的首选项

突出显示文本后,只需键入以下命令即可执行s替换:

代码语言:javascript
复制
%s//<your-replacement-string>

..。因为对s命令的空白搜索将使用上一次搜索的字符串。

票数 41
EN

Stack Overflow用户

发布于 2011-05-30 07:51:08

除非您的视觉选择中包含特殊字符,否则接受的答案效果很好。我把两个脚本(Jeremy Cantrell的和Peter Odding的)拼凑在一起,生成了一个命令,它允许你直观地选择一个你想要查找的字符串,即使它有特殊的正则表达式字符。

代码语言:javascript
复制
" Escape special characters in a string for exact matching.
" This is useful to copying strings from the file to the search tool
" Based on this - http://peterodding.com/code/vim/profile/autoload/xolox/escape.vim
function! EscapeString (string)
  let string=a:string
  " Escape regex characters
  let string = escape(string, '^$.*\/~[]')
  " Escape the line endings
  let string = substitute(string, '\n', '\\n', 'g')
  return string
endfunction

" Get the current visual block for search and replaces
" This function passed the visual block through a string escape function
" Based on this - https://stackoverflow.com/questions/676600/vim-replace-selected-text/677918#677918
function! GetVisual() range
  " Save the current register and clipboard
  let reg_save = getreg('"')
  let regtype_save = getregtype('"')
  let cb_save = &clipboard
  set clipboard&

  " Put the current visual selection in the " register
  normal! ""gvy
  let selection = getreg('"')

  " Put the saved registers and clipboards back
  call setreg('"', reg_save, regtype_save)
  let &clipboard = cb_save

  "Escape any special characters in the selection
  let escaped_selection = EscapeString(selection)

  return escaped_selection
endfunction

" Start the find and replace command across the entire file
vmap <leader>z <Esc>:%s/<c-r>=GetVisual()<cr>/

如果这对任何人更有用的话,我已经在我的vimrc中包含了这个。

票数 28
EN

Stack Overflow用户

发布于 2017-03-26 06:04:25

在Vim7.4中,您可以使用gn运动来选择与当前搜索模式匹配的文本区域。

在正常模式下,使用cgn更改当前选定匹配中的文本(或使用dgn更改要删除的文本)后,可以使用.重复该命令并操作下一个匹配。

有一个an episode of Vimcast展示了这个特性。

票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/676600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档