-2

I have a data as mentioned below.

host_name   Server1.domain.com
contacts    DL - Desktop
contact_groups ravi, raj, rahim
host_name  Server2.domain.com
contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com
contacts   Services,helpdesk,manager

Required Output is below.

host_name Server1.domain.com, contacts ravi,raj,rahim, Contact_group DL-Desktop
host_name Server2.domain.com  contact_groups DL - Server
host_name Server3.domain.com
host_name Server4.domain.com contacts services,helpdesk,manager
  • 1
    This isn't the place to spam links about your website; stop posting them in comments – Michael Mrozek Jun 8 '16 at 14:39
1

I am sure you can do it much easily in awk, but awk doesn't like me much so here is my take on it using everything but the kitchen sink. Assuming that the data is in a file called file1

export output=; while read line; do if [[ "$line" =~ "host_name" ]]; then export output="${output}\n"; fi; export output="${output}, $line"; done < file1 && echo -e $output | sed 's/^, \?//' | sed '/^$/d'

Content of file1

host_name   Server1.domain.com
contacts    ravi, raj, rahim
contact_groups DL - Desktop
host_name  Server2.domain.com
contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com
contacts   Services,helpdesk,manager

Output of the above command

host_name Server1.domain.com, contacts ravi, raj, rahim, contact_groups DL - Desktop
host_name Server2.domain.com, contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com, contacts Services,helpdesk,manager
1
$ sed -e '2,$ s/^host_name/\n&/' ravi.txt | 
    perl -n -e 'if (! m/^$/) {
                    chomp;
                    $line .= $_ . ", "
                };

                if (m/^$/ || eof) {
                    $line =~ s/  +/ /g; # merge multiple spaces into one space
                    $line =~ s/, $//;   # strip the trailing comma
                    print $line,"\n" ;
                    $line=""
                }'
host_name Server1.domain.com, contacts DL - Desktop, contact_groups ravi, raj, rahim
host_name Server2.domain.com, contact_groups DL-Server
host_name Server3.domain.com
host_name Server4.domain.com, contacts Services,helpdesk,manager

First use sed to convert the input to paragraphs (separated by a newline). Then perl to join the lines in each paragraph together and print them out.

This could be done entirely in perl, but I was lazy and decided it was easier to just convert to paragraphs before piping into a simple perl scipt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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