将多个 jq 值通过管道传输到“while read -r";环形 [英] Pipe multiple jq values to "while read -r" loop

查看:34
本文介绍了将多个 jq 值通过管道传输到“while read -r";环形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种干净的方法,在 while 循环中将 2 个 json 字符串值分配给 2 个变量.我正在使用的循环和输入如下.

I am trying to find a clean way to assign 2 json string values to 2 variables within a while loop. The loop and input I am working with are as follows.

输入:

foo='
[
   {
      "name":"name string (more info)",
      "nested_name":{
         "name":"my name",
         "conclusion":"failure",
         "number":11
      }
   },
   {
      "name":"name string (more info)",
      "nested_name":{
         "name":"my other name",
         "conclusion":"failure",
         "number":13
      }
   }
]'

目前我有以下几点:

echo "$foo" | jq ".[].name,.[].nested_name.name" | while read -r foo bar; do
    # do stuff with foo and bar
done

在迭代 1 中,我想要:

In iteration 1, I want:

foo = "name string (more info)" 
bar = "my name"

迭代 2:

foo = "name string (more info)" 
bar = "my other name"

然而,这会产生以下不正确的输出:

However this generates the following incorrect output:

foo = "name 
bar = string (more info)"
foo = "name 
bar = string (more info)"
foo = "my 
bar = name"
foo = "my 
bar = other name"

我一整天都在做这件事,非常感谢任何意见或建议!

I've been at this all day, any input or suggestions would be very much appreciated!

推荐答案

使用两个read,每行一个:

#!/usr/bin/env bash

json='
[
   {
      "name":"name string (more info)",
      "nested_name":{
         "name":"my name",
         "conclusion":"failure",
         "number":11
      }
   },
   {
      "name":"name string (more info)",
      "nested_name":{
         "name":"my other name",
         "conclusion":"failure",
         "number":13
      }
   }
]'


while read -r foo && read -r bar; do
    printf "foo=%s\nbar=%s\n" "$foo" "$bar"
done < <(jq ".[] | .name, .nested_name.name" <<<"$json")


我不得不改变你的 jq 表达式以获得你想要的输出.


I had to change your jq expression to get your desired output.

还要注意对原始 JSON 文本和循环变量使用不同的名称,使用 here string 而不是 echo,并且使用文件重定向而不是管道;如果 while 的主体设置了以后需要的任何变量,则很有用.

Also note using different names for your original JSON text and the loop variable, using a here string instead of echo, and using file redirection instead of a pipeline; useful if the body of the while sets any variables needed later.

另一种方法是将所有 jq 输出读入一个数组,然后对其进行迭代:

An alternative that reads all the jq output into an array and then iterates it:

readarray -t lines < <(jq ".[] | .name, .nested_name.name" <<<"$json")
for (( i = 0; i < ${#lines[@]}; i += 2 )); do
    foo=${lines[i]}
    bar=${lines[i+1]}
    printf "foo=%s\nbar=%s\n" "$foo" "$bar"
done

这篇关于将多个 jq 值通过管道传输到“while read -r";环形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆