16

I suppose tr is a more core method and thus probably a faster way to replace things within a given file.

However tr can only replace equal amounts of characters. meaning...

2 characters can only be replaced with 2 characters which means replacing

\r\n with \n is out of the question via tr

is the next best option sed ?

is sed the most core and fastest way to replacing \r\n with \n in a file given the lack of capabilities in tr ?

would like an example if possible.

Braiam
  • 35,380
  • 25
  • 108
  • 167
user73235
  • 163
  • 1
  • 1
  • 4

2 Answers2

30

With sed, you can do:

sed 's/\r$//'

The same way can do with tr, you only have to remove \r:

tr -d '\r'

although this will remove all instances of \r, not necessary followed by \n.

Rufflewind
  • 115
  • 5
cuonglm
  • 150,973
  • 38
  • 327
  • 406
  • 3
    These two are not identical. The first with replace '\r\n' with '\n' (effectively), but the second will remove all '\r' wherever they appear. It's uncommon for carriage-return to appear in a text file, other than at the end of the line, but it can happen. – ams Jun 30 '14 at 16:56
  • 1
    Usage: `sed 's/\r$//' input_file.txt > output_file.txt` – Roald Jun 27 '20 at 09:18
  • Why is it `\r$` and not `\r\n/\n`? I mean where does it replace against `\n`? – mgutt Jan 03 '23 at 11:08
  • Ah ok `$` is line-ending, which means "remove \r from the end of the line". – mgutt Jan 03 '23 at 11:19
5

OR use dos2unix

for example:

$ echo -ne "1\r\n2" |  od -A n -t x1
 31 0d 0a 32
$ echo -ne "1\r\n2" | dos2unix | od -A n -t x1
 31 0a 32

we can see replace \r\n with \n

Baba
  • 3,159
  • 2
  • 25
  • 39
  • This is not a program in the OP list but in my opinion the cleanest way to do the job. I personally use it every time I need such conversion. – рüффп Jan 30 '17 at 20:50