I'm looking for a way to get a quick view of the hypervisor when looking for a guest virtual machine (running KVM).
I have a script that collects all my hypervisors (with guest VMs) in a single text file separated by a line break (see example below):
Hypervisor: hypervisor1
ID Name State
----------------------------------------------------
1 vm1 running
2 vm2 running
3 vm3 running
4 vm4 running
Hypervisor: hypervisor2
ID Name State
----------------------------------------------------
1 vm1 running
2 vm2 running
3 vm3 running
4 vm4 running
5 vm5 running
6 vm6 running
ETC....
I tried with:
grep -v -E "(-|Name)" file.txt |
awk -F ' ' '{print $2}' |
tr "\n" " " |
sed "s/ * / -> /"
But I get this:
hypervisor1 -> vm1 vm2 vm3 vm4 hypervisor2 vm1 vm2 vm3 vm4 vm5 vm6
My question is: how do I get this displayed?
hypervisor1 -> vm1 vm2 vm3 vm4
hypervisor2 -> vm1 vm2 vm3 vm4 vm5 vm6
etc.. etc...
With awk:
awk '/Hypervisor:/ {printf "%s ->", $2} # row contains Hypervisor:
$0=="" {print ""} # row is empty
$1~/[0-9]/ {printf " %s", $2} # first column contains digit
END {print ""}' file # add a trailing newline
Output:
hypervisor1 -> vm1 vm2 vm3 vm4 hypervisor2 -> vm1 vm2 vm3 vm4 vm5 vm6