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


当前回答

我将假设您是指行尾的回车符(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。

我用的是python,这是我的代码;

end1='/home/.../file1.txt'
end2='/home/.../file2.txt'
with open(end1, "rb") as inf:
     with open(end2, "w") as fixed:
        for line in inf:
            line = line.replace("\n", "")
            line = line.replace("\r", "")
            fixed.write(line)

尝试将DOS文件转换为Unix文件:

fromdos file

古老的学校:

tr -d '\r' < filewithcarriagereturns > filewithoutcarriagereturns

如果你使用的操作系统(如OS X)没有dos2unix命令,但有Python解释器(2.5+版本),这个命令相当于dos2unix命令:

python -c "import sys; import fileinput; sys.stdout.writelines(line.replace('\r', '\n') for line in fileinput.input(mode='rU'))"

它处理命令行上的命名文件以及管道和重定向,就像dos2unix一样。如果您将这一行添加到~/。Bashrc文件(或其他shell的等效配置文件):

alias dos2unix="python -c \"import sys; import fileinput; sys.stdout.writelines(line.replace('\r', '\n') for line in fileinput.input(mode='rU'))\""

... 下次登录时(或运行source ~/.)您将能够在命令行上以与其他示例相同的方式使用dos2unix名称。