Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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 following data with multiple lines

username: joe
empid: 1111
status: resigned

username: tom
emid: 1234

username: kate
empid: 2222
status: resigned

What I want is to get the data in to other file as below

username: joe,empid: 1111,status: resigned
username: tom,empid: 1234
username: kate,empid: 2222,status: resigned

Best Wishes, KJ

share|improve this question
Do you know how to use any of the editors? – Debra Oct 13 '13 at 0:57

Here is a shorter perl version:

perl -000 -ne 's/\n+/,/g; s/,$//g; print "$_\n"' filename.txt

The -000 activates paragraph mode where multiple successive newlines define an input record.

share|improve this answer

I managed to do it using

perl -p -e 's/\n/,/' filename.txt | perl -p -e 's/,,/\n/g' | perl -p -e 's/,\Z/\n/g'

The first command replaces newlines with commas, the second puts the newline back where there where two newlines before and the third one removes the last comma artifact and replaces it with a newline.

It is probably possible to do all of this in one command, but I am not familiar enough with perl to do it. The reason I use it here is that sed does not offer an easy solution to replace newlines.

share|improve this answer

Using gawk,

gawk '{s=$1 $2;for(i=3;i<NF;i+=2) {s=s "," $i $(i+1)}print s}' RS= IFS=":"  input.txt

But note that this "eats" spaces after the "field separator" (:).

share|improve this answer

You can also use tr:

tr '\n' ',' filename.txt
share|improve this answer
This won't work, it will print everything in a single line. Also, tr needs the file to be redirected, tr 'a' 'b' < file.txt. – terdon Oct 13 '13 at 2:59

You must log in to answer this question.

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