在ascii编码中,有两个重要的字符:cr(回车,编码为13)和lf(换行,编码为10)。在编程中,我们通常将它们分别表示为'\r'和'\n'。这些字符用于标记换行,但在不同操作系统中,换行标志的使用方式有所不同。以下是不同操作系统采用的换行符:
在Linux中,可以使用"cat -A [Filename]"命令查看文件中的换行符。如下图所示,Windows形式的换行符显示为'^M$',其中'\r'对应'^M','\n'对应'$'。

将Windows换行符转换为Linux格式时,有以下三种方法可供选择,根据个人喜好选择使用哪一种,当然你也可以选择其他方法。
(1) 使用VI编辑器:在VI的普通模式下打开文件,然后运行命令"set ff=unix",即可将Windows换行符转换为Linux换行符。命令中的"ff"是"file encoding"的缩写。
(2) 使用"dos2unix"命令:如下所示:
[root@localhost test]# dos2unix gggggggg.txt dos2unix: converting file gggggggg.txt to UNIX format ...
要匹配所有文件并将Windows换行符转换为Linux格式,可以使用以下命令:
sed -i 's/\r$//g' *
(3) 使用sed命令删除'\r'字符:
[root@localhost test]# sed -i 's/\r//g' gggggggg.txt
对于需要处理多个文件的换行符转换,通常我们需要替换一个目录及其子目录下的所有文件。我编写了一个简单的脚本来遍历目录和子目录下的所有文件,并将其转换为Linux换行格式。脚本代码如下:
#!/bin/sh
#CheckInput
#Check Whether the input is valid
#0 means not valid
CheckInput()
{
ret=1;
#Check the number of parameter
#And Check whether the argument is a folder
if [ $# -lt 1 ]
then
echo "Please use the command like ./dos2u.sh [Folder]";
ret=0
elif [ ! -d $1 ]
then
echo "Please use an invalid Folder as the shell argument";
ret=0
fi
return $ret;
}
<h1>TraverseFolder</h1><h1>Traser all the files under the folder</h1><p>TraverseFolder()
{
oldPath=<pre class="brush:php;toolbar:false;">pwd
cd $1;
for file in <pre class="brush:php;toolbar:false;">ls<pre class="brush:php;toolbar:false;"> #sed -i 's/\r//g' $file
dos2unix $file
fi
done
cd $oldPath;}
CheckInput $* if [ $ret -ne 1 ] then exit -1 fi
TraverseFolder $1
你也可以直接使用VI命令打开需要替换换行符的文件,并输入":set ff=unix"来设置文件格式为Unix格式。
以上就是操作系统 文件换行符问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号