【问题标题】:Transform file content into json string with jq doesn't work in command substitution使用 jq 将文件内容转换为 json 字符串在命令替换中不起作用
【发布时间】:2021-11-10 12:21:07
【问题描述】:

这是按预期工作的:

$ cat /etc/tfe-config/sources/fluent-bit.conf.tpl | jq -R -s
$ "[OUTPUT]\n    Name               cloudwatch_logs\n    Match              *\n    region             eu-central-1\n    log_group_name     TFE-LogForwarding\n    log_stream_name    TFE-AllLogs"

但是,分配给变量不起作用:

$ MY_VARIABLE=$(cat /etc/tfe-config/sources/fluent-bit.conf.tpl | jq -R -s)
$ echo $MY_VARIABLE 
jq - commandline JSON processor [version 1.5]
Usage: jq [options] <jq filter> [file...]

        jq is a tool for processing JSON inputs, applying the
        given filter to its JSON text inputs and producing the
        filter's results as JSON on standard output.
        The simplest filter is ., which is the identity filter,
        copying jq's input to its output unmodified (except for
        formatting).
        For more advanced filters see the jq(1) manpage ("man jq")
        and/or https://stedolan.github.io/jq

        Some of the options include:
         -c             compact instead of pretty-printed output;
       .... trimmed

我在带有最新 Amazon Linux 2 映像的 AWS EC2 机器上。

这是怎么回事?

文件如下所示:

[OUTPUT]
    Name               cloudwatch_logs
    Match              *
    region             eu-central-1
    log_group_name     TFE-LogForwarding
    log_stream_name    TFE-AllLogs

【问题讨论】:

  • 由于输出包含空格,您需要引用它:MY_VARIABLE="$(cat /etc/tfe-config/sources/fluent-bit.conf.tpl | jq -R -s)"
  • 不幸的是同样的问题。
  • 请分享一个输入文件的例子,我们可以自己试试。
  • @0stone0 赋值的右侧不会进行分词,也不需要引号,除非它是像 a='has space' 这样的字符串。命令替换永远不需要在右侧使用引号。

标签: json bash shell jq


【解决方案1】:

两件事:

  • 您必须为 jq 指定一个过滤器 - 只需 . 即可获取整个输入
  • 一旦在带有空格的变量中,您必须引用该字符串,否则当您打印它时它会以不同的方式显示
var=$(cat /etc/tfe-config/sources/fluent-bit.conf.tpl | jq -R -s '.')
echo "$var" 

相关问答:

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 2016-03-24
    • 2015-03-24
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多