如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
当前回答
我不得不思考同样的问题(在windows方面,但同样适用于Linux)。
令人惊讶的是,没有人提到一种非常自动化的方法,使用旧的zip -ll选项(Info-ZIP)对文本文件进行CRLF <-> LF转换:
zip -ll textfiles-lf.zip files-with-crlf-eol.*
unzip textfiles-lf.zip
注意:这将创建一个ZIP文件,保留原始文件名,但将行结束符转换为LF。然后unzip将解压压缩后的文件,即使用它们的原始名称(但使用lf结尾),从而提示覆盖本地原始文件(如果有的话)。
zip——help的相关摘录:
zip --help
...
-l convert LF to CR LF (-ll CR LF to LF)
其他回答
蒂姆托维迪!
perl -pe 's/\r\n/\n/; s/([^\n])\z/$1\n/ if eof' PCfile.txt
根据戈登·戴维森的回答。
人们必须考虑到……的可能性。
这个问题可以用标准工具解决,但对于粗心的人来说,有很多陷阱,我建议您安装flip命令,这是20多年前由《zoo》的作者Rahul Dhesi编写的。 它在转换文件格式方面做得很出色,例如,避免了二进制文件的无意破坏,如果您只是到处更改您看到的每个CRLF,这有点太容易了……
你可以通过option -c {command}以编程方式使用Vim:
DOS到Unix:
vim file.txt -c "set ff=unix" -c ":wq"
Unix到DOS:
vim file.txt -c "set ff=dos" -c ":wq"
“set ff=unix/dos”表示将文件的fileformat (ff)更改为unix/dos的行尾格式。
":wq"表示将文件写入磁盘并退出编辑器(允许在循环中使用该命令)。
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标志。
在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