in vim, execute this command:
:v/./d
EDIT
with grep: grep -o '^[0-9]\+'
should work without worrying about empty lines. It gives all the leading numbers (ids).
with your command:
vm_ids=$(vim-cmd vmsvc/getallvms|grep -o '^[0-9]\+')
题
vim-cmd vmsvc/getallvms
prints like this:
id virtual machine name
11 VirtualMachine1
15 Virtual Machine 1
6 Virtu al Machin e 1
9 Virtual Machine one
21 VirtualMa chineone
I get the ids using the following:
vm_ids=$(vim-cmd vmsvc/getallvms | awk 'NR>1 {print $1}' | egrep "[0-9]+")
And next I want to loop through them and execute a command against each one so I do this:
i=2
for id in $vm_ids
do
vm_name=$(vim-cmd vmsvc/getallvms | awk -v i=$i -F "[[:space:]]{2,}+" 'NR==i {print $2}' | egrep "$[[:alnum:]]")
echo "Doing something to ID: $id for machine: $vm_name"
$((i++))
done
My script is returning a null
value when it gets to those empty lines.
I made the virtual machine names like this just to demonstrate the variety of ways that a name can be returned. Since ESXi doesn't have tr
installed, how can I remove those lines from my output, or is there a better way of doing this?
解决方案 3
in vim, execute this command:
:v/./d
EDIT
with grep: grep -o '^[0-9]\+'
should work without worrying about empty lines. It gives all the leading numbers (ids).
with your command:
vm_ids=$(vim-cmd vmsvc/getallvms|grep -o '^[0-9]\+')
其他提示
With grep
:
grep . file
With awk
:
awk 'NF' file
However you can replace your command with a single call to awk
:
vm_ids=$(vim-cmd vmsvc/getallvms | awk '/^[0-9]+/{print $1}')
Using sed
:
sed '/^$/d' inputfile
Since you're already piping the output to awk, a better approach would be to replace your command with:
vm_ids=$(vim-cmd vmsvc/getallvms | awk 'NF && NR>1 {print $1}' | egrep "[0-9]+")