I have a yaml file where i need to copy a key:value (when: var) to the task underneath and need to repeat that for each block.
How it looks like now:
- set_fact: something
- set_fact: var_a
- task: do the foo
when: var_a
- task: do the goo
- set_fact: something
- set_fact: var_b
- task: do the fofo
when: var_b
- task: do the gogp
- set_fact: something
- set_fact: var_c
- task: do the fooolo
when: var_c
- task: do the gooolo
How i need it to look like:
- set_fact: something
- set_fact: var_a
- task: do the foo
when: var_a
- task: do the goo
when: var_a
- set_fact: something
- set_fact: var_b
- task: do the fofo
when: var_b
- task: do the gogp
when: var_b
- set_fact: something
- set_fact: var_c
- task: do the fooolo
when: var_c
- task: do the gooolo
when: var_c
From researching how to do this, i think a vim loop could do that but i have no clue how to do that. In case anybody has any hints, i'd be very grateful.
Edit: What i tried. With this i captured the values i needed. (the var_ values)
grep -e set_fact -B1 filterlist_playbook.yml|grep -e "^.*\:"|grep -v "set\_fact\:"|awk -F":" '{print $1}'
I tried this in two different ways.
1 first add the "when:" field and then copy/paste the var_ value Adding the when: field was ok with sed. Pasting the right value sequentially... i do not find info how to do that, my colleagues also do not know.
2 copy/paste the "when: var_" value to the block underneath. Again capturing the right value is ok with sed, pasting it sequentially leaves me scratching my head and googling into oblivion.
CodePudding user response:
Using awk you can do this:
awk -F ': ' '
$1 ~ / when$/ {var = $0}
NF
!NF && prev == "- task" {print var ORS}
{prev = $1}
END {if (prev == "- task") print var}' file
- set_fact: something
- set_fact: somethingelse
- task: do the foo
when: var_a
- task: do the goo
when: var_a
- set_fact: something
- set_fact: somethingelse
- task: do the fofo
when: var_b
- task: do the gogp
when: var_b
- set_fact: something
- set_fact: somethingelse
- task: do the fooolo
when: var_c
- task: do the gooolo
when: var_c
CodePudding user response:
In vim you could do this:
qqstart recording a macro calledq/when:Enter find the next occurrence ofwhen:yyyank the current linejmove the cursor downppaste the line underneathqterminate the macro recording
At this point you can call the macro as many times as you need typing @q.
You may also get to know in advance how many times you need to perform this finding the occurrences of when: with :%s/when://ng, which will print out something like 3 matches on 3 lines. Then you may just type e.g. 3@q to call the macro 3 times.
CodePudding user response:
If ed is available/acceptable.
printf '%s\n' 'g/^[[:space:]]\{1,\}when: var_.*/t.1' ,p Q | ed -s file.yaml
If the output is correct, and in-place editing is neded, change
,p Q
to
w q
I only have GNU ed at hand.
