如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
当前回答
我根据接受的答案做了一个脚本,所以你可以直接转换它,而不需要一个额外的文件,然后删除和重命名。
convert-crlf-to-lf() {
file="$1"
tr -d '\015' <"$file" >"$file"2
rm -rf "$file"
mv "$file"2 "$file"
}
只要确保你有一个像“file1.txt”这样的文件,“file1.txt”。Txt2”不存在,否则将被覆盖。我将此作为存储文件的临时位置。
其他回答
作为Jonathan Leffler的Unix to DOS解决方案的扩展,当你不确定文件当前的行结束符时,可以安全地转换为DOS:
sed '/^M$/! s/$/^M/'
这将在转换为CRLF之前检查该行是否已经在CRLF中结束。
蒂姆托维迪!
perl -pe 's/\r\n/\n/; s/([^\n])\z/$1\n/ if eof' PCfile.txt
根据戈登·戴维森的回答。
人们必须考虑到……的可能性。
我试着
sed 's/^M$//' file.txt
在OS X以及其他一些方法(修复Dos行结束或http://hintsforums.macworld.com/archive/index.php/t-125.html)。没有一个工作,文件保持不变(顺便说一下,需要按Ctrl + V, Enter来重新生成^M)。最后我使用了TextWrangler。它不是严格意义上的命令行,但它可以工作,而且不会抱怨。
这个问题可以用标准工具解决,但对于粗心的人来说,有很多陷阱,我建议您安装flip命令,这是20多年前由《zoo》的作者Rahul Dhesi编写的。 它在转换文件格式方面做得很出色,例如,避免了二进制文件的无意破坏,如果您只是到处更改您看到的每个CRLF,这有点太容易了……
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标志。