【问题标题】:Converting null-terminated lines to JSON strings with jq使用 jq 将 null 终止的行转换为 JSON 字符串
【发布时间】:2020-02-17 03:04:42
【问题描述】:

我想出了一个基于jq 的单行器,它将一系列以空字符结尾的字符串转换为一系列 JSON 字符串:

xargs -0 dash -c 'for i in "$@"; do printf %s "$i" | jq -Rs . ; done' _dummy_

如果可能的话,我想删除 xargs 和/或 dash。有没有办法只用jq 做同样的事情?

示例用法:

# Create a new dir with some funny-named files
mkdir funny
cd funny
touch $'ABC\nDEF' $' GHI\nJKL ' ' - はじめまして - '
# Use find -print0 to list the files
find -type f -print0 |
# Convert the null-terminated lines to JSON strings
xargs -0 dash -c 'for i in "$@"; do printf %s "$i" | jq -Rs . ; done' _dummy_

输出:

"./ - はじめまして - "
"./ GHI\nJKL "
"./ABC\nDEF"

【问题讨论】:

    标签: json string jq nul


    【解决方案1】:

    以下产生您指定的输出:

    find . -type f -print0 | jq -Rs 'split("\u0000")[]'
    

    【讨论】:

    • 鉴于输入是以空字符结尾且不是以空字符分隔的,我想知道为什么拆分操作末尾没有额外的空白字符串。似乎是个特例;将printf 'ABCxDEFxGHIx' | jq -Rs 'split("x")[]' 的输出与printf 'ABC\0DEF\0GHI\0' | jq -Rs 'split("\u0000")[]' 的输出进行比较。很奇怪。
    • -R 选项选择终止 \n\0,除了特殊情况 \n\0
    • 这有记录吗?
    猜你喜欢
    • 2021-09-03
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多