Substituting everything from = to end of the line in VIM

谁都会走 提交于 2019-12-08 02:28:18

问题


Let's say I have several lines like:

$repeat_on =  $_REQUEST['repeat_on'];    
$opt_days = $_REQUEST['opt_day'];  
$opt_days = explode(",", $opt_days);

... and so on.

Let's say I use visual mode to select all the lines: how can I replace everything from = to the end of the line so it looks like:

$repeat_on = NULL;    
$opt_days =  NULL;
$opt_days =  NULL;

回答1:


With the block selected, use this substitute:

s/=.*$/= NULL;

The substitution regex changes each line by replacing anything between = and the end of the line, including the =, with = NULL;.

The first part of the command is the regex matching what is to be replaced: =.*$.

  • The = is taken literally.
  • The dot . means any character.
  • So .* means: 0 or more of any character.
  • This is terminated by $ for end of line, but this actually isn't necessary here: try it also without the $.

So the regex will match the region after the first = in each line, and replace that region with the replacement, which is = NULL;. We need to include the = in the replacement to add it back, since it's part of the match to be replaced.

When you have a block selected, and you hit : to enter a command, the command line will be automatically prefixed with a range for the visual selection that looks like this:

:'<,'>

Continue typing the command above, and your command-line will be:

:'<,'>s/=.*$/= NULL;

Which will apply the replacement to the selected visual block.

If you'll need to have multiple replacements on a single line, you'll need to add the g flag:

:'<,'>s/=.*$/= NULL;/g



回答2:


Some alternatives:

Visual Block (fast)

On the first line/character do... Wl<C-v>jjCNULL;<Esc>bi<Space><Esc>

Macro (faster)

On the first line/character do... qqWllCNULL;<esc>+q2@q

:norm (fastest)

On the first line do... 3:no<S-tab> WllCNULL;<Enter>

Or if you've visually selected the lines leave the 3 off the beginning.



来源:https://stackoverflow.com/questions/12845307/substituting-everything-from-to-end-of-the-line-in-vim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!