How to make sequential lines come in columns based on condition?

Viewed 81

Could anyone help to get desired output like mentioned below?

❯ cat example.txt
hostname a-b-c
services Apache
hostname d-e-f
services Python
hostname g-h-i
vmhostname u-v-w
vmhostname x-y-z

I would like to get output like below

a-b-c Apache
d-e-f Python
g-h-i No services
u-v-w No services
x-y-z No services

I have used awk but getting different output.

❯ cat example.txt | awk 'NR%2{printf $0" ";next;}1'
hostname a-b-c services Apache
hostname d-e-f services Python
hostname g-h-i vmhostname u-v-w
vmhostname x-y-z %
1 Answers

Could you please try following, written and tested with shown samples in GNU awk.

awk '
/hostname/{
  if(val){
    print val,"NO service"
  }
  val=$2
  next
}
/services/{
  print val,$2
  val=""
}
END{
  if(val){
    print val,"NO service"
  }
}' Input_file

Explanation: Adding detailed explanation for above.

awk '                         ##Starting awk program from here.
/hostname/{                   ##checking condition if line has hostname here.
  if(val){                    ##checking condition if val is NOT NULL here.
    print val,"NO service"    ##printing val and string NO service here.
  }
  val=$2                      ##setting val to 2nd field here.
  next                        ##next will skip all statements from here.
}
/services/{                   ##Checking condition if line has services in it then do following.
  print val,$2                ##Printing val and 2nd field here.
  val=""                      ##Nullifying val here.
}
END{                          ##starting END block of this program from here.
  if(val){                    ##checking condition if val is NOT NULL here.
    print val,"NO service"    ##printing val and string NO service here.
  }
}' Input_file                 ##Mentioning Input_file name here.

Output will be as follows.

a-b-c Apache
d-e-f Python
g-h-i NO service
u-v-w NO service
x-y-z NO service
Related