文件格式批量转换(dos to unix)-自动转换^M符号

转载并修改自 如何转换^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命令并不支持递归选项,因此借用findxargs实现批量处理。

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的编码,因为这部分修改是没有意义的,所以需要批量转换。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值