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


当前回答

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

fromdos file

其他回答

如果你使用的操作系统(如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名称。

我用的是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)

事情是这样的,

%0d是回车字符。使它与Unix兼容。我们需要使用下面的命令。

dos2unix fileName。extension fileName.extension

有一个名为dos2unix的实用程序存在于许多系统上,并且可以在大多数系统上轻松安装。

Cat input.csv | sed 's/\r/\n/g' > output.csv

为我工作