0

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

1
  • Do you know how to use any of the editors?
    – Debra
    Oct 13, 2013 at 0:57

4 Answers 4

3

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.

0

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.

0

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" (:).

-1

You can also use tr:

tr '\n' ',' filename.txt
1
  • 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, 2013 at 2:59

You must log in to answer this question.

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