Home > OS >  Use jq to add string to each element of a list
Use jq to add string to each element of a list

Time:01-18

I would like to write all the direcory names of a parent inside a list. I'm using the tree command to achieve this as well as jq.

That's what I have so far:

directories_found=$(tree -J -d -L 1 | jq -c '.[0].contents | map(.name)').map(.name)

The tree comand returns this before the pipe:

directories_found=[{"type":"directory","name": ".","contents":[ {"type":"directory","name":"AppBackend","contents":[ ]}, {"type":"directory","name":"list-folder-action","contents":[ ]} ]}, {"type":"report","directories":2} ]

And then, after applying jq, the output I see is this:

["AppBackend","list-folder-action"]

Looks awesome. But I'd like to edit these values but also keep the list structure.

My goal is to add a chunk of text before each element, like this:

["example/AppBackend","example/list-folder-action"]

I just started using jq. How could I do this?

CodePudding user response:

As a supplement to @pmf's answer, it is perhaps worth mentioning that you can specify the prefix on the command-line. Also, if you wanted to keep the tree structure, you could run jq like so:

jq -c --arg prefix example/ '.[0].contents |= map($prefix   .name)'
  • Related