Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have got a text file with a list of first names, and I am trying to replace newline with ,.

Here is the command I am using

sed 's/\
/,/g' file

while the reverse is working

sed 's/,/\
/g' file

it replaces , with newline.

share|improve this question

sed is not able to eat newlines in a simple way. sed works on a line-by-line basis, so it can only add newlines, not remove them. But you can effectively do some sed gymnastics by storing two consecutive lines. You may also want to have a look at tr, which is able to replace characters, for example:

tr '\n' , < file

Also, with many tools you can use '\n' to represent the line feed character (used for UNIX line breaks).

Like Stephane pointed, tr will replace all the line feeds (including the last one). You may prefer to use paste, which will join the lines using a specified delimitier:

paste -sd, file
share|improve this answer
tr '\n' , will transliterate every newline character including the last one. paste -sd, file is generally more appropriate (joins the lines with ,) as you don't make assumptions on how lines are implemented under the scene. Also why concatenating a single file? – Stéphane Chazelas Feb 5 '13 at 17:05
Yeah, right, I totally forgot that paste could be used here, and it does indeed solve the problem with the last newline (one hack is adding ;echo, but that's more of a dirty hack and still leaves a last ,); as for concatenating a single file, you can see that in the question the OP does mention a single file as an argument to sed... – njsg Feb 5 '13 at 17:08
njsg, I think Stephane was suggesting to not use cat when there is no actual concatenation to be done, ie. implying to use <file tr '\n' , or tr '\n' , <file instead, thereby avoiding an unnecessary process. – Peter.O Feb 6 '13 at 1:53
Peter.O, right I've edited this to include Stephane's suggestions and notes. – njsg Feb 21 '13 at 11:03

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.