首页 > 解决方案 > parsing two multi-line grep results to a single bash asociative array

问题描述

I'm retrieving filtered text from a group of emails by using these two commands:

1)

curl -u$username:$password --silent "https://mail.google.com/mail/feed/atom" |  grep -oPm1 "(?<=<summary>The host is: )(\S+)+" | sed '1d'

2)

curl -u$username:$password --silent "https://mail.google.com/mail/feed/atom" |  grep -oPm1 "(?<=the serial is\s)(\w+)+" | sed '1d'

each one returns:

1)

xy36 
xy34 
xy32
xy30 
xy29 
xy28 
xy26

2)

Xooz4woo
Oyaith4k
AiN7fie4
ongae6Ro
phoh6fiR
Ohfoh0eM

and i need that data to be parsed to an associative array in bash, in a way i can do a loop write/read it, and use each entry on my code. The array should be:

machines{
{xy36,Xooz4woo}
{xy34 Oyaith4k}
{xy32, AiN7fie4}
{xy30, ongae6Ro}
{xy29, phoh6fiR}
{xy28, Ohfoh0eM}}

so i can access it like:

echo "${machines[xy36]}"
result: Xooz4woo

how can i do that???

标签: arraysbashgrep

解决方案


Put the result of each in an array, then loop over the array indexes.

declare -A machines
hosts=($(first command))
serials=($(second command))
for ((i=0; i < ${#hosts[@]}; i++))
do
    machines[${hosts[$i]}]=${serials[$i]}
done

推荐阅读