从一行中的shell命令中提取多个变量

时间:2016-01-05 15:48:24

标签: shell output ksh

我需要获得命令返回给我的一些行。新例子:

$ Return_Data
HOSTNAME:xpto.com.br 
IP:255.255.255.0 
DISKSPACE:1TB 
LOCATION:argentina 

我只需要LOCATION和IP线路,我需要在一行中收集这些信息。我该怎么办?我可以使用awk,shell,ksh等...

1 个答案:

答案 0 :(得分:1)

最干净的解决方案本身并不是单线。

typeset -A data                   # Create an associative array.
while IFS=: read -r key value; do # Iterate over records, splitting at first :
  data[$key]=$value               # ...and assign each to that map
done < <(Return_Data)             # ...with your command as input.

# ...and, to use the extracted values:
echo "Hostname is ${data[HOSTNAME]}; location is ${data[LOCATION]}"

那就是说,你当然可以把所有这些行与;放在一起:

# extract content
typeset -A data; while IFS=: read -r key value; do data[$key]=$value; done < <(Return_Data)

# demonstrate its use
echo "Hostname is ${data[HOSTNAME]}; location is ${data[LOCATION]}"