Here it is:
#!/usr/bin/env bash
files=('alpha.txt' 'beta.txt' 'delta with space name.txt')
# Filling sample files
printf 'wibble' >'alpha.txt'
printf 'fu\nbar' >'beta.txt'
cat >'delta with space name.txt' <<'EOF'
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
EOF
# Stream the test files names (1 per line)
printf '%s\n' "${files[@]}" |
xargs -L 1 -I {} jq -sR --arg key {} '{ ($key): .}' {} | jq -s 'add'
xargs -L 1 -I {}
: Executes a command by passing each line from stdin
while substituting curly braces by the file name.
xargs
then runs the jq
command to create the filename key and value content of file objects:
jq -sR --arg key {} '{ ($key): .}' {}
Finally, the stream of JSON objects is piped into a final jq -s 'add'
to re-assemble it, into a merged object with "key": "value"
pairs:
jq -s 'add'
And finally the actual output of all this:
{
"alpha.txt": "wibble",
"beta.txt": "fu\nbar",
"delta with space name.txt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n"
}
Processing all files with a single jq
:
xargs -I {} jq -sR '{(input_filename):.}' {} | jq -s add
The caution about using input_filename
from man jq
:
input_filename
Returns the name of the file whose input is currently being filtered. Note that this will not work well unless jq is running in a UTF-8 locale.