Putting "\n" in my .c or .cpp file using vim

I'm using vim to make my programs in c/c++ and I would like to know how can I put "n" (which represents a newline) in my code or use "%" using :%s .

For instance, sometimes I forget to put "%" in front of "d" or "f" in many lines or forget to put "n" in some printf() calls.

printf("This is my d code.", x);

But the following command does not work, it puts a space in place of "n"!

:%s/<code.>/code.n/gc

or

:%s/<d>/%d/gc

How can I do what I want?


The :help s/n has the answer:

  n    insert a <NL> (<NUL> in the file)
    (does NOT break the line)              *s/n*

You'll also find the solution there: to insert a literal backslash, escape it by doubling ; to split the line, a r has to be used . Yes, this is inconsistent, and it works differently in similar tools like sed , but that's unfortunately how it is.

Notes

  • The n doesn't insert a space, but the special <NL> character, which usually is shown as ^@ .
  • The <code.> isn't right; to match a literal period, you have to escape it: . . Else, it matches any character. Likewise, the . usually isn't a keyword character, so the > boundary wouldn't match.
  • You don't need to repeat the match text in the replacement, you can use & for it. Also read up on capture groups ( :help /( ) and the submatch references :help s/1 . This is a better way:
  • :%s/<code./&n/gc
    

    (I don't see a problem with the second substitution.)


    You want to insert the two-character sequence n , not a literal newline (the latter would create a syntax error).

    A sample line to be changed is:

    printf("This is my d code.", x);
    

    One problem with your attempt:

    :%s/<code.>/code.n/gc
    

    is that there is no word boundary between the . and the " following the word code . The other problem is that in the target is used to escape special characters (for example you can refer to a / character as / ), so the must itself be escaped.

    This should do the job:

    :%s/<code."/code.n"/gc
    

    A more general solution might be:

    :g/printf/s/"/n"/egc
    

    which offers to replace " by n" on each line that contains printf -- but that will miss any printf calls that span more than one line.

    As for replacing the d by %d , the command you have in your question:

    :%s/<d>/%d/gc
    

    is correct.

    链接地址: http://www.djcxy.com/p/49338.html

    上一篇: 文件以字符串形式存储在bash中

    下一篇: 在我的.c或.cpp文件中使用vim放置“\ n”