【问题标题】:xargs: how to have literal double-quotes in replacement?xargs:如何替换文字双引号?
【发布时间】:2014-09-07 05:55:10
【问题描述】:

我有一个 JSON 对象的源文件,每行一个,如下所示:

来源:

{"_id":"1","name":"one"}
{"_id":"2","name":"two"}
{"_id":"3","name":"three"}

我想将每一行发送到一个

curl -X POST -H "application/json" myURL -d '<REPLACEMENT>'

我尝试时双引号不会使其卷曲

<source xargs -I % curl -X POST -H "application/json" myURL -d '%'

我尝试在 curl 命令中转义引号,后来我用 \" 替换了源文件中的所有双引号。我发现没有版本可以工作。

另一种使用 seq 和 sed 将每一行写入临时文件的方法 curl -d @temp 不适合我。

有没有优雅的解决方案,还是我必须编写一个带循环的脚本?

【问题讨论】:

    标签: json bash curl xargs


    【解决方案1】:

    尝试使用--data-urlencode:

    <source xargs -I % curl -X POST -H "application/json" myURL --data-urlencode '%'
    

    该选项可以与其他格式一起使用。请参阅curl 的手册。你也可以试试--data-binary

    【讨论】:

    • 谢谢。没有帮助。我需要将 % 周围的单引号转义为 \'%\' - 但无论是在 urendcode 还是二进制模式下,内部双引号都不会出现。 curl 在接收到损坏的 json 时的行为更糟​​糕。
    【解决方案2】:

    这是一个有趣的问题。必须有更好的解决方案(也许 konsolebox 有什么用),但是用 \" 替换所有 " 会起作用:

    $ echo '"hello"'
    "hello"
    $ echo '"hello"' | xargs echo
    hello
    $ echo '"hello"' | sed 's/"/\\"/g' | xargs echo
    "hello"
    

    【讨论】:

    • 事实上,我需要将两级引号发送到循环 curl:内部 " 是 json 语法的一部分,外部 ' 限制 -d 参数的值。我尝试转义源,但 curl -d '%' 我没有运气。也许再试一次。
    【解决方案3】:

    GNU Parallel 专门用于处理 xargs 对特殊字符的不良处理:

    <source parallel curl -X POST -H "application/json" myURL -d {}
    

    它不仅会正确引用 ",它还会正确引用 any 字符串,因此它会被 curl 解释为单个参数。

    额外的好处:您的查询将并行运行 - 每个 cpu 一个查询。

    【讨论】:

    • 谢谢,听起来不错!我很幸运:parallel 是一个已知的自制配方 - 所以它已安装 - 稍后再试。感谢到目前为止的提示!
    • 好的,“parallel”而不是 xargs 确实有助于这种变化:H 值引用也必须被转义:&lt;t.json parallel -t curl -X POST -H \'Content-Type: application/json\' http://xxxx.iriscouch.com/xxxx -d {} ... curl 然后被调用一个 d 值未加引号的 JSON 字符串,所有内部双引号和空格都已转义。当 json 字段值包含引号时可能会失败;)
    【解决方案4】:

    应该做的伎俩:

    cat source.json | xargs -0 -I {} curl {}
    

    来自man xargs

      -0, --null
             Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (ev‐
             ery  character  is  taken  literally).  Disables the end of file string, which is treated like any other argument.  Useful
             when input items might contain white space, quote marks, or backslashes.  The GNU find -print0 option produces input suit‐
             able for this mode.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      相关资源
      最近更新 更多