2

I have textfile with CRLF line terminators. The file contains two lines of text (displayed in Vim) :

foo
bar

Say I want to find pattern foo and replace the entire line with goo, so I run:

sed -i 's/foo.*/goo/' textfile

After the operation textfile shows in Vim like this:

goo
bar^M

My question is: Why has the previously hidden carriage return become visible in Vim?

gortsu
  • 126
  • 8

1 Answers1

3

The command:

sed -i 's/foo.*/goo/' textfile

removed the \r from the end of the line since \r is just an arbitrary char for sed on UNIX, matched by .*.

Looks like Vim is smart enough to not display the ^M for Windows style carriage returns as long as they are used consistently in the file. Because of the above sed command they are not used consistently any more as it only removes the \r from lines matching foo.*.

If that is a problem for you I recommend to use:

sed -i 's/foo.*/goo\r/' textfile

sydill's comment pointed me to the right manual section which describes this behaviour: :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". ...

Community
  • 1
  • 1
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • This answers my question and offers a solution to the issue. Thank you! – gortsu Feb 09 '17 at 11:07
  • 1
    This is precisely what's happening, but maybe could be worded _consistently_ instead of _consequently_? There is a useful paragraph in `:h file-formats` that I'd add to this answer as well (If you start editing...Only when ALL lines end in , 'fileformat' is set to "dos", otherwise it is set to "unix") – sidyll Feb 09 '17 at 11:10
  • 1
    Let me change/add that. Thanks for the comment! – hek2mgl Feb 09 '17 at 11:11