为什么 sed 使行终止符在 vim 中可见
Why does sed make line terminators visible in vim
我有 textfile
带有 CRLF 行终止符。该文件包含两行文本(显示在 Vim 中):
foo
bar
说我想找到模式 foo
并用 goo
替换整行,所以我 运行:
sed -i 's/foo.*/goo/' textfile
运行后textfile
在Vim中显示如下:
goo
bar^M
我的问题是:为什么之前隐藏的马车 return 在 Vim 中变得可见?
命令:
sed -i 's/foo.*/goo/' textfile
从行尾删除了 \r
,因为 \r
只是 UNIX 上 sed 的任意字符,由 .*
.
匹配
看起来 Vim 足够聪明,不会显示 Windows 风格马车 returns 的 ^M,只要它们被使用 一致 在文件中。由于上面的 sed 命令,它们不再被一致使用,因为它只从匹配 foo.*
.
的行中删除 \r
如果这对您来说是个问题,我建议您使用:
sed -i 's/foo.*/goo\r/' textfile
将我指向描述此行为的正确手册部分::help file-formats
:
... If you start editing a new file and the 'fileformats' option is not empty
(which is the default), Vim will try to detect whether the lines in the file
are separated by the specified formats. When set to "unix,dos", Vim will
check for lines with a single (as used on Unix and Amiga) or by a
pair (MS-DOS). Only when ALL lines end in , 'fileformat' is set
to "dos", otherwise it is set to "unix". When 'fileformats' includes "mac",
and no characters are found in the file, 'fileformat' is set to "mac". ...
我有 textfile
带有 CRLF 行终止符。该文件包含两行文本(显示在 Vim 中):
foo bar
说我想找到模式 foo
并用 goo
替换整行,所以我 运行:
sed -i 's/foo.*/goo/' textfile
运行后textfile
在Vim中显示如下:
goo bar^M
我的问题是:为什么之前隐藏的马车 return 在 Vim 中变得可见?
命令:
sed -i 's/foo.*/goo/' textfile
从行尾删除了 \r
,因为 \r
只是 UNIX 上 sed 的任意字符,由 .*
.
看起来 Vim 足够聪明,不会显示 Windows 风格马车 returns 的 ^M,只要它们被使用 一致 在文件中。由于上面的 sed 命令,它们不再被一致使用,因为它只从匹配 foo.*
.
\r
如果这对您来说是个问题,我建议您使用:
sed -i 's/foo.*/goo\r/' textfile
:help file-formats
:
... If you start editing a new file and the 'fileformats' option is not empty (which is the default), Vim will try to detect whether the lines in the file are separated by the specified formats. When set to "unix,dos", Vim will check for lines with a single (as used on Unix and Amiga) or by a pair (MS-DOS). Only when ALL lines end in , 'fileformat' is set to "dos", otherwise it is set to "unix". When 'fileformats' includes "mac", and no characters are found in the file, 'fileformat' is set to "mac". ...