[英]Using JQ to create a JSON file from a list of files
I want to create a JSON file from a list of files like:我想从如下文件列表中创建一个 JSON 文件:
$ ls -r *
folder1/
file1.pdf
file2.pdf
file3.pdf
folder2/
file4.pdf
file5.pdf
file6.pdf
I want a json file that looks like this:我想要一个看起来像这样的 json 文件:
{
'folder1' : [ 'file1.pdf', 'file2.pdf', 'file3.pdf' ],
'folder2' : [ 'file4.pdf', 'file5.pdf', 'file6.pdf' ]
}
For now I am able to create the list of files with jq
but not sure how to name them.现在我可以用
jq
创建文件列表,但不知道如何命名它们。 This is what I am doing now:这就是我现在正在做的事情:
$ ls folder | jq -R -s 'split("\n") -[""]'
[
"file1.pdf",
"file2.pdf",
"file3.pdf"
]
Thanks a lot for the help!非常感谢您的帮助!
PS. PS。 Additionally, I need to include a prefix in the name of files.
此外,我需要在文件名中包含一个前缀。 I can try to do it with
sed
but if maybe there is an easier way to do it here, that would be even better.我可以尝试用
sed
,但如果这里有更简单的方法,那就更好了。
You shouldn't parse the output of ls
.您不应该解析
ls
的 output 。 Pass folder1/file1.pdf
, folder1/file2.pdf
, etc. to JQ as positional arguments instead, and parse them in there. folder1/file1.pdf
, folder1/file2.pdf
等作为位置 arguments 传递给 JQ,并在那里解析它们。
jq -n 'reduce ($ARGS.positional[] / "/") as [$k, $v] (.; .[$k] += ["prefix-\($v)"])' --args */*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.