I try to write script in shell/bash that will convert yaml directory structure to full paths (for further mkdir -p it). Yaml is my choice because of human-editability. Structure example is:

- Downloads
    - Music
    - Movies
- University
    - First year
        - English
        - Maths
    - Second year

So I want to replace first-level with current dir (realpath .), for example, /home/maeda/Downloads, second with parent dir's full path (for example, /home/maeda/Downloads/Music)

So I want to achieve this result:

/home/maeda/University/First year
/home/maeda/University/First year/English
/home/maeda/University/First year/Maths
/home/maeda/University/Second year

How to achieve it?


1 Answer 1


Assuming that your YAML file is valid, such as

    First year:
    Second year:

you may use

yq -r --arg prefix "$(realpath .)" 'paths | [ $prefix, .[] ] | join("/")' file.yaml

where yq is from https://kislyuk.github.io/yq/

This uses a jq expression to get the "paths" from the document. A "path" in this context is a representation of any specific entry in the document itself, so the path of the First year array is the array [ 'University', 'First year' ] (written using JSON notation).

These path arrays may be joined with / as the delimiter using join("/").

I'm also passing the output of realpath . into yq as the value of the internal variable $prefix. This value is added to the front of each of the path arrays before passing them through join("/"), which means that it will be prepended to the pathnames outputted by the yq command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .