2

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.

2 Answers 2

1

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
2
  • 1
    Carriage return (to answer OP's actual question) would be \r, not \n. Commented Sep 11, 2015 at 9:28
  • 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. Commented Sep 12, 2015 at 0:29
0

tr is a better solution but you asked how to do it in sed.

with ansi -c quoting:

sed -E 's/'$'\r''/,/' file

sed $'s/\r/,/' file

without ansi -c quoting:

cr=$(printf '\r')
sed 's/'"$cr"'/,/' file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .