如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
当前回答
这个问题可以用标准工具解决,但对于粗心的人来说,有很多陷阱,我建议您安装flip命令,这是20多年前由《zoo》的作者Rahul Dhesi编写的。 它在转换文件格式方面做得很出色,例如,避免了二进制文件的无意破坏,如果您只是到处更改您看到的每个CRLF,这有点太容易了……
其他回答
使用AWK你可以做到:
awk '{ sub("\r$", ""); print }' dos.txt > unix.txt
使用Perl你可以做到:
perl -pe 's/\r$//' < dos.txt > unix.txt
这个问题可以用标准工具解决,但对于粗心的人来说,有很多陷阱,我建议您安装flip命令,这是20多年前由《zoo》的作者Rahul Dhesi编写的。 它在转换文件格式方面做得很出色,例如,避免了二进制文件的无意破坏,如果您只是到处更改您看到的每个CRLF,这有点太容易了……
有趣的是,在Windows上的Git Bash中,sed ""已经做到了:
$ echo -e "abc\r" >tst.txt
$ file tst.txt
tst.txt: ASCII text, with CRLF line terminators
$ sed -i "" tst.txt
$ file tst.txt
tst.txt: ASCII text
我的猜测是,sed在从输入读取行时忽略它们,并且总是将Unix行结束符写入输出。
安装dos2unix,然后就地转换文件
dos2unix <filename>
将转换后的文本输出到不同的文件使用
dos2unix -n <input-file> <output-file>
你可以在Ubuntu或Debian上安装它
sudo apt install dos2unix
或者在macOS上使用Homebrew
brew install dos2unix
The solutions posted so far only deal with part of the problem, converting DOS/Windows' CRLF into Unix's LF; the part they're missing is that DOS use CRLF as a line separator, while Unix uses LF as a line terminator. The difference is that a DOS file (usually) won't have anything after the last line in the file, while Unix will. To do the conversion properly, you need to add that final LF (unless the file is zero-length, i.e. has no lines in it at all). My favorite incantation for this (with a little added logic to handle Mac-style CR-separated files, and not molest files that're already in unix format) is a bit of perl:
perl -pe 'if ( s/\r\n?/\n/g ) { $f=1 }; if ( $f || ! $m ) { s/([^\n])\z/$1\n/ }; $m=1' PCfile.txt
注意,这将把文件的统一版本发送到标准输出。如果你想用一个统一的版本替换这个文件,添加perl的-i标志。