【问题标题】:What is wrong with this bash script [duplicate]这个bash脚本有什么问题[重复]
【发布时间】:2021-09-11 14:45:14
【问题描述】:
#!/bin/bash
filename='delete'

while read p; do 
    jq 'if .tweet | test('\"$p\"'; "i") then . |= . + {vendor: '\"$p\"'} else empty end' sfilter.json
done < $filename

当我使用 variable = "hello world" 但不是 "hello" 时,我不断收到此错误 简而言之,只要字母中有空格,就会导致此错误。

但是直接在shell上执行似乎没有错误。

jq: error: syntax error, unexpected $end, expecting QQSTRING_TEXT or QQSTRING_INTERP_START or QQSTRING_END (Unix shell quoting issues?) at <top-level>, line 1:
if .tweet | test("sdas                  
jq: 1 compile error

但是当我在 shell 上运行命令时,它运行良好。有什么想法吗?

编辑: 输入删除文件

sdas 广告

【问题讨论】:

  • 请分享输入文件。
  • @0stone0 完成添加输入文件。

标签: json bash jq


【解决方案1】:

p 的值传递给您的 jq 程序,如下所示:

while read p; do
    jq --arg p "$p" 'if .tweet | test($p; "i") then . |= . + {vendor: $p} else empty end' sfilter.json
done < $filename

发生 shell 错误是因为您错误地连接了字符串。 试试这个:

p=value
JQ_program='if .tweet | test("'"$p"'"; "i") then . |= . + {vendor: "'"$p"'"} else empty end'
echo "$JQ_program"

# result
# if .tweet | test("value"; "i") then . |= . + {vendor: "value"} else empty end

【讨论】:

    【解决方案2】:

    不要使用字符串插值生成动态jq 过滤器。通过--arg 选项传递值。

    #!/bin/bash
    filename='delete'
    
    while IFS= read -r p; do 
        jq --arg p "$p" 'if .tweet | test($p; "i") then . |= . + {vendor: $p} else empty end' sfilter.json
    done < "$filename"
    

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2015-10-27
      • 2015-05-24
      相关资源
      最近更新 更多