Remove carriage returns in text file via the Terminal in Mac OS X 10.10 (Yosemite)

8,990

This isn’t really specific to Mac OS X; the same concept works on most any Linux/Unix OS. But while you could do this in sed (stream editor) you could also use tr (translate characters) like this:

tr '\r' , < foo.txt

So if the contents of foo.txt are this:

123
456
789

The output of that tr command would then be:

123,456,789,

And to then output that command’s results to a file add > bar.txt to the end like this:

tr '\r' , < foo.txt > bar.txt
Share:
8,990

Related videos on Youtube

Needs More Documentation
Author by

Needs More Documentation

Updated on September 18, 2022

Comments

  • Needs More Documentation
    Needs More Documentation almost 2 years

    I’m trying to replace all carriage returns with a comma in a text file but I must be using the sed command improperly.

    Since I can echo -e "\x0D"and yield the carriage return I tried sed -e 's/open/'$(echo "\x0D")'/' 1.txt > 2.txt to no avail. 1.txt contains the carriage return, as you may have inferred. That command creates 2.txt which contains text x0D.

  • Thomas Dickey
    Thomas Dickey almost 9 years
    Carriage return (to answer OP's actual question) would be \r, not \n.
  • Needs More Documentation
    Needs More Documentation almost 9 years
    Ah! Yes, I am aware of this solution. I was looking for how to do it in Sed, if possible. I spent hours trying to use unicode or /r with sed but couldn't figure out how. I probably should have saved you the time by posting that in my initial query. Apologies.
  • Giacomo1968
    Giacomo1968 almost 9 years
    @NeedsMoreDocumentation Nah. Don’t apologize. I didn’t realize this was sed specific and this answer was fairly simple for me to post. So if it can help someone, all good.