18

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.

1
  • What exactly does "Most Core" mean? Commented Jun 4, 2015 at 23:57

2 Answers 2

32

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.

4
  • 4
    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. Commented Jun 30, 2014 at 16:56
  • 1
    Usage: sed 's/\r$//' input_file.txt > output_file.txt Commented Jun 27, 2020 at 9:18
  • Why is it \r$ and not \r\n/\n? I mean where does it replace against \n? Commented Jan 3, 2023 at 11:08
  • Ah ok $ is line-ending, which means "remove \r from the end of the line". Commented Jan 3, 2023 at 11:19
7

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

1
  • 1
    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. Commented Jan 30, 2017 at 20:50

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.