我正在寻找一种方法,以便在查找来宾虚拟机(运行KVM(时快速查看系统管理程序。
我有一个脚本,它将我的所有管理程序(与来宾虚拟机(收集在一个用换行符分隔的文本文件中(见下面的示例(:
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....
我尝试过:
grep -v -E "(-|Name)" file.txt |
awk -F ' ' '{print $2}' |
tr "n" " " |
sed "s/ * / -> /"
但我明白了:
hypervisor1 -> vm1 vm2 vm3 vm4 hypervisor2 vm1 vm2 vm3 vm4 vm5 vm6
我的问题是:如何显示?
hypervisor1 -> vm1 vm2 vm3 vm4
hypervisor2 -> vm1 vm2 vm3 vm4 vm5 vm6
etc.. etc...
带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
输出:
hypervisor1->vm1-vm2-vm3-vm4hypervisor2->vm1 vm2 vm3 vm4 vm5 vm6
对于您显示的示例,您可以尝试以下操作吗。
awk '
/Hypervisor:/{
if(value1){
print value,value1
}
found=value1=""
value=$NF
next
}
/ID/{
found=1
next
}
found && match($0,/vm[0-9]+/){
value1=(value1?value1 OFS:"")substr($0,RSTART,RLENGTH)
}
END{
if(value1){
print value,value1
}
}
' Input_file
解释:添加以上详细解释。
awk ' ##Starting awk program from here.
/Hypervisor:/{ ##Checking condition if line contains Hypervisor: then do following.
if(value1){ ##Checking if value1 is NOT NULL.
print value,value1 ##Printing value and value1 here.
}
found=value1="" ##Nullify found and value1 here.
value=$NF ##Setting value as last field here.
next ##next will skip all further statements from here.
}
/ID/{ ##Checking condition if ID is found in current line then do following.
found=1 ##Setting found to 1 here.
next ##next will skip all further statements from here.
}
found && match($0,/vm[0-9]+/){ ##Checking if found is SET and match function to match vm values.
value1=(value1?value1 OFS:"")substr($0,RSTART,RLENGTH)
##Creating value1 which has matched sub string and keep adding its values to it.
}
END{ ##Starting END block of this program from here.
if(value1){ ##Checking condition if value1 is set then do following.
print value,value1 ##Printing value and value1 here.
}
}
' Input_file ##Mentioning Input_file name here.
这可能对你有用(GNU sed(:
sed -E '/Hypervisor:/{s/.*: //;:a;x;/./{s/n/ -> /;s// /g;p};x;h;d}
/^s*[0-9]+s*(S+).*/{s//1/;H};$!d;ba' file
将相关详细信息存储在保留空间中,并在管理程序更改或文件结束时,将存储的值操作为所需的格式。