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

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


当前回答

有趣的是,在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行结束符写入输出。

其他回答

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

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

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/..../ '文件。

使用AWK你可以做到:

awk '{ sub("\r$", ""); print }' dos.txt > unix.txt

使用Perl你可以做到:

perl -pe 's/\r$//' < dos.txt > unix.txt

蒂姆托维迪!

perl -pe 's/\r\n/\n/; s/([^\n])\z/$1\n/ if eof' PCfile.txt

根据戈登·戴维森的回答。

人们必须考虑到……的可能性。

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