在Unix中从文件中删除所有回车\r的最简单方法是什么?


当前回答

古老的学校:

tr -d '\r' < filewithcarriagereturns > filewithoutcarriagereturns

其他回答

我将假设您是指行尾的回车符(CR,“\r”,0x0d),而不是盲目地在文件中(据我所知,您可能将它们放在字符串中间)。使用这个测试文件,只在第一行的末尾加上CR:

$ cat infile
hello
goodbye

$ cat infile | od -c
0000000   h   e   l   l   o  \r  \n   g   o   o   d   b   y   e  \n
0000017

如果在您的系统上安装了Dos2unix,那么它是正确的选择:

$ cat infile | dos2unix -U | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

如果由于某种原因dos2unix对您不可用,那么sed将执行此操作:

$ cat infile | sed 's/\r$//' | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

如果由于某些原因sed对你不可用,那么ed会以一种复杂的方式来做:

$ echo ',s/\r\n/\n/
> w !cat
> Q' | ed infile 2>/dev/null | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

如果你没有在你的盒子上安装任何这些工具,你有比试图转换文件更大的问题:-)

如果你是一个Vi用户,你可以打开文件并删除回车符:

:%s/\r//g

或与

:1,$ s/^M//

请注意,您应该通过按ctrl-v和ctrl-m键入^M。

tr -d '\r' < infile > outfile

看到tr (1)

这又是一个解决方案……因为总还有一个问题:

perl -i -pe 's/\r//' filename

它很好,因为它可以在我使用过的所有unix/linux版本中工作。

对于UNIX……我注意到dos2unix从我的UTF-8文件中删除了Unicode头。在git bash (Windows)下,下面的脚本似乎工作得很好。它使用sed。注意,它只删除行尾的回车符,并保留Unicode标头。

#!/bin/bash

inOutFile="$1"
backupFile="${inOutFile}~"
mv --verbose "$inOutFile" "$backupFile"
sed -e 's/\015$//g' <"$backupFile" >"$inOutFile"