转载并修改自 如何转换^M行末符号,侵删。
文章目录
1. 问题描述
1.1 问题描述
Windows(dos)和Linux(unix)系统中,对于格式处理存在差异,比如“行末符”的表示不同,Windows下面是\r\n
(CR-回车,LD-换行),而Linux则是\n
(LD-换行)。
因此,如果在Windows下面编辑的脚本文件,如shell脚本文件,在Linux下面执行失败,会提示多一个^M
符号,用VIM打开也会发现增加这个符号,或通过 cat -A 文件名
看到这些隐藏字符。
注意:^M
使用 ctrl+V ctrl+M
输入
1.2 查看
直接vim filename无法看到^M
,可以搭配-b参数确认
vim -b filename
2. 解决办法
2.1 用VIM打开,设置编码为unix
:set fileformat=unix
或
: set ff=unix
然后,保存,结尾unix格式。
2.2 使用VIM的替换功能,替换行末的\r符号即可
:%s/^M//g
2.3 使用sed来进行批量处理
sed ’s/^M//’ filename > tmp_filename
2.4 批量处理(dos2unix,需sudo权限安装格式转换工具)
sudo apt-get install dos2unix
可直接使用dos2unix filename
直接转换。
但考虑到批量及递归修改,dos2unix命令并不支持递归选项,因此借用find
和xargs
实现批量处理。
find . * | xargs dos2unix (对当前目录下面的所有文件执行转换格式的命令)
或
find -type f | xargs dos2unix
另外,dos2unix自动识别的格式转换可能并不能达到批量效果(可能是因为目录下文件格式混乱),所以保险起见,最好加上指定的转换参数,如:
find -type f | xargs dos2unix -U
附,dos2unix --help
$ dos2unix --help
usage:
dos2unix [--verbose|-v] [--test|-t] [--force|-f] \
[--<x>2<y>|--auto|-<Z>] \
[<file name> [...]]
where:
--auto, -A output will be set based upon auto-detection
of source format
--d2u, -U perform DOS -> UNIX conversion
--m2u, -T perform MAC -> UNIX conversion
--u2d, -D perform UNIX -> DOS conversion
--u2m, -M perform UNIX -> MAC conversion
--d2m, -O perform DOS -> MAC conversion
--m2d, -C perform MAC -> DOS conversion
--force suppress internal conversion type corrections
based on autodetected input format
--skipbin, -b skip binary files
--test, -t don't write any conversion results; useful with
--verbose to just report on source type
--verbose, -v print extra information on stderr
--version, -V print version information on stderr
- when no options are given then input format will be automatically detected
and converted as follows:
DOS -> UNIX
MAC -> UNIX
UNIX -> DOS
- same as above applies if --auto option is used
- when no file is given, then stdin is used as input and stdout as output
- binary files will be skipped automatically if option --skipbin
(or -b) is used
- stray '\r' characters (without a following '\n') in files in DOS format are
reported but only conversion 'DOS -> Unix' affects them (they are skipped)
- stray '\n' characters in files in MAC format are not detected for now
注意:
dos2unix需要root权限,我开始的时候没有用sudo运行,提示转换失败,后来利用sudo执行即可。
3. 问题的根源
在Windows下面拉取Git上面的代码,结果给版本库所有的文件都加上了行末符号,而在Linux下面再次编辑该文件就发现所有的问题都出现问题,提交的时候又不能
把所有的文件都提交成Windows的编码,因为这部分修改是没有意义的,所以需要批量转换。