《Linux Shell》笔记之dos2unix

本文介绍了如何使用dos2unix工具将Windows格式的文本文件转换为Unix格式,解决Windows与Unix系统间文件因换行符差异导致的问题。通过实例展示了转换前后文本的区别,并演示了dos2unix命令的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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$


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值