假设我们有一个文本,我进入可视模式并选择了一些文本。如何快速搜索突出显示的文本并将其替换为其他内容?
发布于 2013-04-11 03:39:18
这种快速而简单的映射搜索视觉上突出显示的文本(不覆盖h寄存器),并且不使用终端相关+寄存器:
" search for visually hightlighted text
vnoremap <c-f> y<ESC>/<c-r>"<CR>
如果您不喜欢ctrl-f,请将其更改为您的首选项
突出显示文本后,只需键入以下命令即可执行s
替换:
%s//<your-replacement-string>
..。因为对s
命令的空白搜索将使用上一次搜索的字符串。
发布于 2011-05-30 07:51:08
除非您的视觉选择中包含特殊字符,否则接受的答案效果很好。我把两个脚本(Jeremy Cantrell的和Peter Odding的)拼凑在一起,生成了一个命令,它允许你直观地选择一个你想要查找的字符串,即使它有特殊的正则表达式字符。
" 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中包含了这个。
发布于 2017-03-26 06:04:25
在Vim7.4中,您可以使用gn
运动来选择与当前搜索模式匹配的文本区域。
在正常模式下,使用cgn
更改当前选定匹配中的文本(或使用dgn
更改要删除的文本)后,可以使用.
重复该命令并操作下一个匹配。
有一个an episode of Vimcast展示了这个特性。
https://stackoverflow.com/questions/676600
复制相似问题