bash中的结构解决方案

时间:2019-02-06 11:32:40

标签: bash shell scripting

我有一个来自API请求的字符串,它看起来像大json,每个元素都有2个字段(名称,href),在此操作之后,我将此名称添加到了数组中:

  declare 


       cursor cur1 is select * from address where aid in
        (select Min(aid) from address group by
        country,state,city,street_name,locality,house_no);

       cursor cur2 is select * from address;


        cur1_aid                address.aid%type;
        cur1_country            address.country%type;
        cur1_city               address.city%type;
        cur1_state              address.state%type;
        cur1_streetAddress      address.street_name%type;
        cur1_locality           address.locality%type;
        cur1_houseNo            address.house_no%type;


        cur2_aid                address.aid%type;
        cur2_country            address.country%type;
        cur2_city               address.city%type;
        cur2_state              address.state%type;
        cur2_streetAddress      address.street_name%type;
        cur2_locality           address.locality%type;
        cur2_houseNo            address.house_no%type;



begin 
         open cur1;
            loop
            fetch cur1 into cur1_aid,cur1_country,cur1_state,cur1_city,cur1_streetAddress,cur1_locality,cur1_houseNo;
            exit when cur1%NOTFOUND;
                open cur2;
                    loop
                    fetch cur2 into  cur2_aid,cur2_country,cur2_state,cur2_city,cur2_streetAddress,cur2_locality,cur2_houseNo;
                    exit when cur2%NOTFOUND;
                        if(cur1_country=cur2_country) and (cur1_state=cur2_state) and (cur1_city=cur2_city) and (cur1_streetAddress=cur2_streetAddress) and (cur1_locality=cur2_locality) and (cur1_houseNo=cur2_houseNo) then
                            if (cur1_aid!=cur2_aid) then
                                    update employee_add set aid=cur1_aid where aid=cur2_aid;
                                    delete address where aid=cur2_aid;
                            end if;
                        end if;
                    end loop;
                close cur2;
            end loop;
        close cur1;
    DELETE FROM employee_add a
    WHERE ROWID > (SELECT MIN(ROWID) FROM employee_add b
    WHERE b.eid=a.eid and b.aid=a.aid
    );
    end;
    /

但是我需要在数组usergroups_array中存储2个变量(名称和href)。我的意思是下一个解决方案:

数组:

str_from_api="$(user_groups_json "limit=100" | jq -r '.items | .[].name')"
readarray -t usergroups_array <<< "$str_from_api"

该数组长100条记录。在需要对每个名称和每个href执行操作之后,这就是为什么我需要访问此结构的每个元素的原因。

我该如何实现?

更新

json:

str_from_api=(name:"Test name", href: "Test href")

1 个答案:

答案 0 :(得分:0)

这是一种快速而肮脏的尝试,目的是使您的输出进入Bash循环。

user_groups_json "limit=100" |
jq -r '.items | .[] | (._meta.href + " " + .name)' |
while read -r href name; do
    echo "'$name' has href '$href'"
    : do stuff with these variables here
done

您说您希望将它们放在一个数组中,但是然后说明您希望一次处理它们;因此,将整个列表存储在一个您只能访问一次的变量中似乎是多余的。