Changing multiple lines in to single line with spaces in linux

0

1

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

KumarJohn

Posted 2013-10-13T00:43:41.123

Reputation: 223

Do you know how to use any of the editors? – Debra – 2013-10-13T00:57:59.550

Answers

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.

terdon

Posted 2013-10-13T00:43:41.123

Reputation: 45 216

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.

Tim

Posted 2013-10-13T00:43:41.123

Reputation: 1 811

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

ShinTakezou

Posted 2013-10-13T00:43:41.123

Reputation: 176

-2

You can also use tr:

tr '\n' ',' filename.txt

cmdrptt

Posted 2013-10-13T00:43:41.123

Reputation: 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 – 2013-10-13T02:59:21.553