0

for example, I want to comment out all printLog() functions in a file:

//printLog();
printLog();
//printLog();

but some printLog() are already comment out, and replacing printLog() with //printLog() directly would result in:

////printLog();
//printLog();
////printLog();

is it possible to replace "printLog();" into "//printLog();" but not "printLog();" originally in "//printLog();"?

1

You could anchor your search pattern to the beginning of the line:

:%s@^printLog@//&

and maybe take leading white space into account for more safety:

:%s@^\s*printLog@//&

Breaking it down…

  • :s allows you to use other characters than forward slashes as separators, that's handy when your search pattern or replacement contain forward slashes. Here I use @ but you can use any character except a-zA-Z0-9\"|. See :help e146.
  • The ^ atom represents the beginning of the line so ^printLog will only match printLog if it is at the beginning of a line. See :help /^.
  • In the "safe" variant, we add "zero or more white space characters" (\s*) between the beginning of the line and printLog. See :help \s.
  • In the replacement part, we reuse the matched text with &. See :help s/\&.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.