将JQ NULL分隔的输出存储在bash数组中 [英] Storing JQ NULL-delimited output in bash array

查看:79
本文介绍了将JQ NULL分隔的输出存储在bash数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash 4.4.12上使用jq 1.5和这种单线IFS=_ read -r -a a < <(jq -ncj '["a","b","c"][]+"_"') ; printf '%s\n' "${a[@]}",我得到了正确定界的输出

on bash 4.4.12 using jq 1.5 with this one-liner IFS=_ read -r -a a < <(jq -ncj '["a","b","c"][]+"_"') ; printf '%s\n' "${a[@]}" I get a properly delimited output

a

b

c

分别对于元素a,b和c,但是,如果我尝试使用空分隔符来执行相同的操作,例如:IFS= read -r -a a < <(jq -ncj '["a","b","c"][]+"\u0000"') ; printf '%s\n' "${a[@]}",那么我只会得到一个包含的数组元素

for elements a, b and c respectively, BUT if I try the same thing with a null delimiter like so: IFS= read -r -a a < <(jq -ncj '["a","b","c"][]+"\u0000"') ; printf '%s\n' "${a[@]}" then I would get only one array element containing

abc

为什么这个工作不如预期?

Why doesn't this work like expected?

此外,如果您尝试使用IFS= read -r -d '' -a a < <(jq -ncj '["a","b","c"][]+"\u0000"') ; printf '%s\n' "${a[@]},您将惊讶地得到只有第一个" a "数组的数组.元素:

Furthermore, if you try IFS= read -r -d '' -a a < <(jq -ncj '["a","b","c"][]+"\u0000"') ; printf '%s\n' "${a[@]}, you will be surprised to get an array with only the first "a" element:

a

我的目标是找到一种方法,而不用任何循环遍历元素.

My goal is to find an approach without iterating over elements with any kind of a loop.

**readarray -d**不是解决方案,因为我需要这段代码才能在4.4版之前的bash中运行

**readarray -d** is not a solution since i need the piece of code to run in bash prior to version 4.4

推荐答案

使用readarray,它获得的-d类似于bash 4.4中read上的相同选项:

Use readarray, which gained a -d analogous to the same option on read in bash 4.4:

$ readarray -d $'\0' -t a < <(jq -ncj '["a","b","c"][]+"\u0000"')
$ declare -p a
declare -a a=([0]="a" [1]="b" [2]="c")

-d ''也可以;由于外壳程序字符串以null终止,因此从技术上讲''是包含null字符的字符串.

-d '' works as well; since shell strings are null terminated, '' is, technically, the string containing the null character.

在没有readarray -d支持的情况下,您可以将while循环与read一起使用,该循环应在bash的任何版本中都可以使用:

Without readarray -d support, you can use a while loop with read, which should work in any version of bash:

a=()
while read -d '' -r item; do
    a+=("$item")
done < <( jq -ncj '["a","b","c"][]+"\u0000"' )

这是您所能做的最好的事情,除非您对数组元素有所了解,从而使您可以选择一个不属于任何元素的替代定界符.

This is the best you can do unless you know something about the array elements that would let you pick an alternate delimiter that isn't part of any of the elements.

这篇关于将JQ NULL分隔的输出存储在bash数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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