Karl Karl - 6 months ago 28
Linux Question

How can search replace multiple lines in a file using sed

I have this in multiple files

- "{{inventory_dir}}/common/vars/{{type1}}.yml"
- "{{inventory_dir}}/common/vars/{{type2}}.yml"
- "{{inventory_dir}}/common/vars/{{type3}}.yml"
- "{{inventory_dir}}/common/vars/{{type4}}.yml"
bla bla

The lines path can vary so its not constant

Now every time i have to chnage that in multiple files by hand. I was lokking for something using sed which i can use to replace.

Is it possible that i have
file which contain the code which i want to replace like

- "{{inventory_dir}}/common/vars/{{type22}}.yml"
- "{{inventory_dir}}/common/vars/{{type22}}.yml"
- "{{inventory_dir}}/common/vars/{{type32}}.yml"
- "{{inventory_dir}}/common/vars/{{type42}}.yml"

Then sed find above patterns in files and replace with above template at same location.

My sed knowledge is only to replace some one line of code in multiple files like

find files/ -type f -name "*.yml" -exec sed -i -re 's/\{\{inventory_dir\}\}\/vars\/common\.yml/\{\{inventory_dir\}\}\/common\/vars\/common.yml/g' {} \;

But i am not sure how can i do with multiple lines.

I am thinking of findinglines between
and then replace with template but i am not sure how can i read that


sed is for simple substitutions on individual lines, that is all. For anything else you should be using awk. This is untested but will be very close to what you need:

awk '
NR==FNR { new = new $0 ORS; next }
inVF && ($1 != "-") { inVF=0 }
/vars_files:/ { inVF=1; printf "%s", new }
' template file.yml