0

I've come up with a jq-based one-liner that converts a sequence of null-terminated strings to a sequence of JSON strings:

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

I'd like to cut xargs and/or dash out of it if possible. Is there a way to do the same thing with just jq?

Example usage:

# 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_

Output:

"./ - はじめまして - "
"./ GHI\nJKL "
"./ABC\nDEF"
peak
  • 105,803
  • 17
  • 152
  • 177
psmay
  • 1,001
  • 7
  • 17

1 Answers1

1

The following produces the output you've specified:

find . -type f -print0 | jq -Rs 'split("\u0000")[]'
peak
  • 105,803
  • 17
  • 152
  • 177
  • 1
    Given that the input is null-terminated and not null-delimited, I wonder why a split operation doesn't have an extra blank string at the end. Seems to be a special case; compare the output of `printf 'ABCxDEFxGHIx' | jq -Rs 'split("x")[]'` to that of `printf 'ABC\0DEF\0GHI\0' | jq -Rs 'split("\u0000")[]'`. Weird. – psmay Feb 18 '20 at 02:29
  • The -R option chomps a terminating `\n` and `\0` except for the special case `\n\0`. – peak Feb 18 '20 at 02:47
  • Is this documented? – psmay Feb 24 '20 at 15:23