将shell变量传递给awk不会产生预期的输出

时间:2017-01-12 19:03:32

标签: shell awk

我试图将一组变量输出到CSV格式的字符串中,例如

a11-ai-001,Gi1/0/28,207,f8b1.56d1.ff64,Dell,10.76.207.47,DHCP_Allocated,USHAGWITV102

使用以下代码:

echo $switch | awk '{ print "switch="$1 }'
echo $accessport | awk '{ print "accessport="$1 }'
echo $accessvlan | awk '{ print "accessvlan="$1 }'
echo $mac | awk '{ print "mac="$1 }'
echo $macvendor | awk '{ print "macvendor="$1 }'
echo $ip | awk '{ print "ip="$1 }'
echo $ipstate | awk '{ print "ipstate="$1 }'
echo $hostname | awk '{ print "hostname="$1 }'

echo $switch $accessport $accessvlan $mac $macvendor $ip $ipstate $hostname  | awk -v '{ print $1" "$2" "$3" "$4" "$5" "$6" "$7" "$8 }'

awk -v var1="$switch" -v var2="$accessport" -v var3="$accessvlan" -v > var4="$mac" -v var5="$macvendor" -v var6="$ip" -v var7="$ipstate" -v > var8="$hostname" 'BEGIN{print > var1","var2","var3","var4","var5","var6","var7","var8 }'

我收到了这个输出:

  

开关= A11-AI-001
  accessport = GI1 / 0/28
  accessvlan = 207
  MAC = f8b1.56d1.ff64
  macvendor =戴尔
  IP = 10.76.207.47
  ipstate = DHCP_Allocated
  主机名= USHAGWITV102
  ,USHAGWITV102001,GI1 / 0/28207,f8b1.56d1.ff64,戴尔,10.76.207.47,DHCP_Allocated
  ,USHAGWITV102001,Gi1 / 0 / 28,207,f8b1.56d1.ff64,Dell,10.76.207.47,DHCP_Allocated

当我想要的是这个:

  

开关= A11-AI-001
  accessport = GI1 / 0/28
  accessvlan = 207
  MAC = f8b1.56d1.ff64
  macvendor =戴尔
  IP = 10.76.207.47
  ipstate = DHCP_Allocated
  主机名= USHAGWITV102
  A11-AI-001,GI1 / 0/28207,f8b1.56d1.ff64,戴尔,10.76.207.47,DHCP_Allocated,USHAGWITV102
  a11-ai-001,Gi1 / 0 / 28,207,f8b1.56d1.ff64,Dell,10.76.207.47,DHCP_Allocated,USHAGWITV102

我做错了什么?

1 个答案:

答案 0 :(得分:2)

ipstate的值以回车结束,当显示""将光标移动到行的开头。然后awk输出的其余部分将覆盖行开头的文本。您可以在问题点解决此问题

awk ... -v var7="${ipstate%$'\r'}" ...

或在首次分配ipstate的值时处理它。