如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
当前回答
在Linux上,使用sed很容易将^M (Ctrl + M)转换为*nix换行符(^J)。
在CLI中就像这样,文本中会有一个换行符。然而,\将^J传递给sed:
sed 's/^M/\
/g' < ffmpeg.log > new.log
你可以使用^V (Ctrl + V), ^M (Ctrl + M)和\(反斜杠)当你输入:
sed 's/^V^M/\^V^J/g' < ffmpeg.log > new.log
其他回答
蒂姆托维迪!
perl -pe 's/\r\n/\n/; s/([^\n])\z/$1\n/ if eof' PCfile.txt
根据戈登·戴维森的回答。
人们必须考虑到……的可能性。
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标志。
作为Jonathan Leffler的Unix to DOS解决方案的扩展,当你不确定文件当前的行结束符时,可以安全地转换为DOS:
sed '/^M$/! s/$/^M/'
这将在转换为CRLF之前检查该行是否已经在CRLF中结束。
对于Mac OS X,如果您安装了Homebrew (http://brew.sh/):)
brew install dos2unix
for csv in *.csv; do dos2unix -c mac ${csv}; done;
确保您已经复制了文件,因为这个命令将在适当的位置修改文件。 -c mac选项使开关与OS X兼容。
你可以使用AWK。将记录分隔符(RS)设置为匹配所有可能的换行符的正则表达式。并将输出记录分隔符(ORS)设置为unix样式的换行符。
awk 'BEGIN{RS="\r|\n|\r\n|\n\r";ORS="\n"}{print}' windows_or_macos.txt > unix.txt