linux输出按主机名grep内部ip

linux输出按主机名grep内部ip,linux,bash,shell,Linux,Bash,Shell,关于linux输出的问题: 使用gcloud列出我的虚拟机实例: HOSTNAME="chef-production2-doctor-simulator01" gcloud compute instances list |grep $HOSTNAME chef-production2-doctor-simulator01 us-central1-b n1-standard-1 10.128.0.2 x.x.x.x RUNNING 如何对内部

关于linux输出的问题: 使用
gcloud
列出我的虚拟机实例:

HOSTNAME="chef-production2-doctor-simulator01"
gcloud compute instances list |grep $HOSTNAME
chef-production2-doctor-simulator01 us-central1-b n1-standard-1                         10.128.0.2  x.x.x.x   RUNNING
如何对内部ip进行grep并将其输出到bash变量

INTERNAL_IP="$(gcloud compute instances list |grep $HOSTNAME)"

选择列的常用工具有:
cut
sed
awk
。当然,
perl

awk
通常是最短的解决方案,但您必须学习它的语法

gcloud compute instances list | \
awk '/chef-production2-doctor-simulator01/ { print $2 }'

可能就是你要找的。您可能需要明确说明分隔符。很难说在上面的示例中使用了哪些分离器。

您可以像这样尝试:

var INTERNAL_IP="$(gcloud compute instances list | grep chef-production2-doctor-simulator01 | tr -s "  " | cut -d ' ' -f4)"
tr-s“”删除所有双空格 剪切-d'-f4剪切ip

或者正如anony提到的(哪个更好):


谢谢@avivb,但这不是问题。问题不是很清楚,请给出输出以及您想要实现的目标。谢谢,如果主机名在变量$hostname中,您可以编辑您的答案吗?并将响应放在变量中。您应该做这一部分来提高shell脚本编写技能。例如,当使用双引号而不是单引号时,如何在
awk
命令中转义
$
。你需要找出索引/分隔符-我无法在你的计算机上测试!
var INTERNAL_IP="$(gcloud compute instances list | awk '/chef-production2-doctor-simulator01/ { print $4 }'")