如何在 bash 中使用 jq 创建 for 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34426915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:03:09  来源:igfitidea点击:

How to create for-loops with jq in bash

bashfor-loopvariable-expansion

提问by crocefisso

I'm trying to split a json file into various json files. The input (r1.json) looks like :

我正在尝试将 json 文件拆分为各种 json 文件。输入 (r1.json) 看起来像:

 {

    "results" : [

                {
            content 1
}
,
{
            content 2
}
,
{
            content n
}

    ]
}

I'd like the output to be n files : 1.json, 2.json, n.json. Respectively containing {content 1}, {content 2} and {content n}.

我希望输出为 n 个文件:1.json、2.json、n.json。分别包含{content 1}、{content 2}和{content n}。

I tried :

我试过 :

for i in {0..24}; do cat r1.json | jq '.results[$i]' >> $i.json; done

But I have the following error: error: i is not defined

但我有以下错误:错误:我没有定义

采纳答案by crocefisso

While the above answers are correct, note that interpolating shell variables in jq scripts is a terrible idea for all but the most trivial of scripts. On any of the solutions provided, replace the following:

虽然上述答案是正确的,但请注意,在 jq 脚本中插入 shell 变量对于除最微不足道的脚本之外的所有脚本来说都是一个糟糕的主意。在提供的任何解决方案上,替换以下内容:

jq ".results[$i]"

With the following:

具有以下内容:

jq --arg i "$i" '.results[$i | tonumber]'

回答by shellter

Try

尝试

for i in {0..24}; do cat r1.json | jq ".results[$i]" >> $i.json; done

Note that shell variables can't be expanded inside of single-quotes.

请注意,shell 变量不能在单引号内展开。

IHTH

IHTH

回答by Mad Physicist

The single quotes are probably what is messing you up. Bash variables are not expanded in single quotes. You are passing a literal string .results[$i]to jq. Try double quotes instead:

单引号可能是什么让你搞砸了。Bash 变量不在单引号中展开。您正在将文字字符串传递.results[$i]jq. 试试双引号:

for i in {0..24}; do
    cat r1.json | jq ".results[$i]" >> $i.json
done