删除文件中的 ^M 字符

有时候,我们在 Linux 中打开曾在 Win 中编辑过的文件时,会在行尾看到 ^M 字符。虽然,这并不影响什么,但心里面还是有点不痛快。如果想要删除这些 ^M 字符,可以使用 Vim 来轻松搞定它。

在 Vim 的命令模式中输入 :%s/^M$//g 后,回车即会自动删除该文件中的所有 ^M 字符。

那么,这句命令到底是什么意思呢?% 指匹配整个文件,s 是置换的意思,^M 注意要用 Ctrl + V Ctrl + M 来输入,M 后面的 $ 代表匹配行尾的内容,最后的 g 则表示每行中匹配到的内容都要置换。

理解了命令的含义,就好变通使用了,比如说,要将某个文件中的 Vim 全部替换成 VIM,则可以使用这样的命令::%s/Vim/VIM/g

Read More:

  • No related posts

8 Comments

  1. 1 Romeo Commented @ 2006-10-29 22:08Reply to this comment

    Thanks for your tip, very useful.

  2. 2 zeal Commented @ 2006-10-30 2:23Reply to this comment

    ubuntu中有个pakcage叫做tofrodos,安装以后,里面有两个程序 --- dos2unix, unix2dos,dos2unix应该可以用来完成这篇文章里描述的转换。这两条命令(也有叫做fromdos, todos)应该在绝大部分unix,linux系统下都可以找到。

  3. 3 nomas Commented @ 2006-10-30 11:50Reply to this comment

    批量的话貌似可以这样:

    find /path -name "*.后缀" | xargs dos2unix

  4. 4 Toy Commented @ 2006-10-30 18:22Reply to this comment

    @zeal, nomas:谢谢补充新的方法。

  5. 5 Livid Commented @ 2006-10-30 18:35Reply to this comment

    For bunk operations, you can:

    1, apt-get install flip 2, dos to unix: flip -u 3, usage: man flip

    Flip is so useful.

  6. 6 Toy Commented @ 2006-10-30 20:00Reply to this comment

    @Livid:又是一种好方法。谢谢。

    PS.呵呵,达到了抛砖引玉的效果。

  7. 7 Ryun Commented @ 2006-10-31 2:24Reply to this comment

    i often use this line to strip character ^M

    %s/\r//g

  8. 8 Think in Read » links for 2006-10-31 Pingbacked @ 2006-10-31 9:22Reply to this comment

    [...] LinuxTOY » 删除文件中的 ^M 字符 (tags: linux) [...]