How can I change a file's encoding with vim?

前端 未结 5 1624
庸人自扰
庸人自扰 2020-11-30 16:02

I\'m used to using vim to modify a file\'s line endings:

$ file file
file: ASCII text, with CRLF line terminators
$ vim file
:set ff=mac
:wq
$ file file
file         


        
相关标签:
5条回答
  • 2020-11-30 16:43

    It could be useful to change the encoding just on the command line before the file is read:

    rem On MicroSoft Windows
    vim --cmd "set encoding=utf-8" file.ext
    # In *nix shell
    vim --cmd 'set encoding=utf-8' file.ext
    

    See starting, --cmd.

    0 讨论(0)
  • 2020-11-30 16:47

    While using vim to do it is perfectly possible, why don't you simply use iconv? I mean - loading text editor just to do encoding conversion seems like using too big hammer for too small nail.

    Just:

    iconv -f utf-16 -t utf-8 file.xml > file.utf8.xml
    

    And you're done.

    0 讨论(0)
  • 2020-11-30 16:48

    Just like your steps, setting fileencoding should work. However, I'd like to add one "set bomb" to help editor consider the file as UTF8.

    $ vim file
    :set bomb
    :set fileencoding=utf-8
    :wq
    
    0 讨论(0)
  • 2020-11-30 16:51

    From the doc:

    :write ++enc=utf-8 russian.txt

    So you should be able to change the encoding as part of the write command.

    0 讨论(0)
  • 2020-11-30 16:54

    Notice that there is a difference between

    set encoding

    and

    set fileencoding

    In the first case, you'll change the output encoding that is shown in the terminal. In the second case, you'll change the output encoding of the file that is written.

    0 讨论(0)
提交回复
热议问题