Remove carriage return in Unix

2018-12-31 08:25发布

What is the simplest way to remove all the carriage returns \r from a file in Unix?

16条回答
旧人旧事旧时光
2楼-- · 2018-12-31 08:47
tr -d '\r' < infile > outfile

See tr(1)

查看更多
听够珍惜
3楼-- · 2018-12-31 08:48

The simplest way on Linux is, in my humble opinion,

sed -i 's/\r//g' <filename>

The strong quotes around the substitution operator 's/\r//' are essential. Without them the shell will interpret \r as an escape+r and reduce it to a plain r, and remove all lower case r. That's why the answer given above in 2009 by Rob doesn't work.

And adding the /g modifier ensures that even multiple \r will be removed, and not only the first one.

查看更多
栀子花@的思念
4楼-- · 2018-12-31 08:51

sed -i s/\r// <filename> or somesuch; see man sed or the wealth of information available on the web regarding use of sed.

One thing to point out is the precise meaning of "carriage return" in the above; if you truly mean the single control character "carriage return", then the pattern above is correct. If you meant, more generally, CRLF (carriage return and a line feed, which is how line feeds are implemented under Windows), then you probably want to replace \r\n instead. Bare line feeds (newline) in Linux/Unix are \n.

查看更多
余生无你
5楼-- · 2018-12-31 08:52

Old School:

tr -d '\r' < filewithcarriagereturns > filewithoutcarriagereturns
查看更多
看风景的人
6楼-- · 2018-12-31 08:52

Once more a solution... Because there's always one more:

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

It's nice because it's in place and works in every flavor of unix/linux I've worked with.

查看更多
裙下三千臣
7楼-- · 2018-12-31 08:52

I've used python for it, here my code;

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)
查看更多
登录 后发表回答