如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?

dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?


当前回答

一个更简单的没有程序的AWK解决方案:

awk -v ORS='\r\n' '1' unix.txt > dos.txt

从技术上讲,“1”是您的程序,因为AWK在给定选项时需要一个。

或者,内部解决方案是:

while IFS= read -r line;
do printf '%s\n' "${line%$'\r'}";
done < dos.txt > unix.txt

其他回答

作为Jonathan Leffler的Unix to DOS解决方案的扩展,当你不确定文件当前的行结束符时,可以安全地转换为DOS:

sed '/^M$/! s/$/^M/'

这将在转换为CRLF之前检查该行是否已经在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标志。

Use:

tr -d "\r" < file

看一下使用sed的例子:

# In a Unix environment: convert DOS newlines (CR/LF) to Unix format.
sed 's/.$//'               # Assumes that all lines end with CR/LF
sed 's/^M$//'              # In Bash/tcsh, press Ctrl-V then Ctrl-M
sed 's/\x0D$//'            # Works on ssed, gsed 3.02.80 or higher

# In a Unix environment: convert Unix newlines (LF) to DOS format.
sed "s/$/`echo -e \\\r`/"            # Command line under ksh
sed 's/$'"/`echo \\\r`/"             # Command line under bash
sed "s/$/`echo \\\r`/"               # Command line under zsh
sed 's/$/\r/'                        # gsed 3.02.80 or higher

使用sed -i进行就地转换,例如sed -i 's/..../ '文件。

在Bash 4.2及更新版本中,您可以使用类似这样的方法来剥离后面的CR,它只使用Bash内置:

if [[ "${str: -1}" == $'\r' ]]; then
    str="${str:: -1}"
fi

你可以通过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"表示将文件写入磁盘并退出编辑器(允许在循环中使用该命令)。