dos2unix- windows文本格式转换unix格式
平时工作中,可能需要把文件在windows和unix平台之间相互传送,观察到在windows, 每行结尾出是\n\r (换行回车符号),在unix, 每行结尾是\n(换行符号)。
如果Unix系统下的文件在Windows里打开的话,所有文字会变成一行;而Windows里的文件在Unix下打开的话,在每行的结尾可能会多出一个^M符号。
例子:下面例子描述windows 里的文件在Unix下打开的话,行结尾多出了一个^M符号
1. 在windows 上新建一个文件,输入一行句子并且回车
2. 传送此文件,从windows 到linux 目录下(我放在这个目录下/home/test/tmp)
test@sha:~/tmp>ls
WindowsFormat.txt
3. 每个末尾都有^M (\r 回车符),通常是看不出来的,需要使用命令"cat -A WindowsFormat.txt",来查看
test@sha:~/tmp>cat -A WindowsFormat.txt
This is fromwindows^M$
注意: ^M(回车符,相当于\r) $(换行符, 相当于\n)
4. 此时,我们看到末尾有符号^M$,如果在末尾增加字符话,发生下面情况:字符this 被tail 替代了,tail没有加在末尾
test@sha-colline-node-h:~/tmp>sed 's/$/&tail/g' WindowsFormat.txt
tail is from windows
为了解决这个问题,需要把windows文件转换,有两种方法:
方法 1: 使用命令 dos2unix 格式转换test@sha:~/tmp> dos2unix WindowsFormat.txt
dos2unix: converting file WindowsFormat.txt to UNIX format ...
使用cat命令可以查看到符号^M (\r 回车符),没有了
test@sha:~/tmp> cat -A WindowsFormat.txt
This is from windows$
在末尾添加字符,成功!
test@sha:~/tmp> sed 's/$/&tail/g' WindowsFormat.txt
This is from windowstail
方法 2: 去掉 "\r" ,用命令sed -i 's/\r//' WindowsFormat.txt
test@sha:~/tmp> sed -i 's/\r//' WindowsFormat.txt
使用cat命令可以查看到符号^M (\r 回车符),没有了
test@sha:~/tmp> cat -A WindowsFormat.txt
This is from windows$