如何在Vim中用换行符替换字符 [英] How to replace a character by a newline in Vim
问题描述
我正在尝试用新行替换当前文件中的每个,
:
I'm trying to replace each ,
in the current file by a new line:
:%s/,/\n/g
但它会插入看起来像^@
的内容,而不是实际的换行符.该文件不在DOS模式下.
But it inserts what looks like a ^@
instead of an actual newline. The file is not in DOS mode or anything.
我该怎么办?
如果您像我一样好奇,请检查问题 为什么\还可以是Vim的换行符吗? .
If you are curious, like me, check the question Why is \r a newline for Vim? as well.
推荐答案
使用\r
代替\n
.
用\n
替换会在文本中插入一个空字符.要获取换行符,请使用\r
. 搜索换行符时,您仍然会使用\n
.这种不对称性是由于\n
和\r
所做的事情稍有不同:
Use \r
instead of \n
.
Substituting by \n
inserts a null character into the text. To get a newline, use \r
. When searching for a newline, you’d still use \n
, however. This asymmetry is due to the fact that \n
and \r
do slightly different things:
\n
匹配行尾(换行符),而\r
匹配回车符.另一方面,在替换中,\n
插入一个空字符,而\r
插入一个换行符(更准确地说,它被视为输入< CR> ).这是一个小的非交互式示例,使用Vim命令行功能进行了说明(换句话说,您可以将以下内容复制并粘贴到终端中以运行它). xxd
显示结果文件的十六进制转储.
\n
matches an end of line (newline), whereas \r
matches a carriage return. On the other hand, in substitutions \n
inserts a null character whereas \r
inserts a newline (more precisely, it’s treated as the input <CR>). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). xxd
shows a hexdump of the resulting file.
echo bar > test
(echo 'Before:'; xxd test) > output.txt
vim test '+s/b/\n/' '+s/a/\r/' +wq
(echo 'After:'; xxd test) >> output.txt
more output.txt
Before:
0000000: 6261 720a bar.
After:
0000000: 000a 720a ..r.
换句话说,\n
已将字节0x00插入到文本中. \r
插入了字节0x0a.
In other words, \n
has inserted the byte 0x00 into the text; \r
has inserted the byte 0x0a.
这篇关于如何在Vim中用换行符替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!