Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multi-line plain text

Assuming you have plenty of yaml files (or anything similar) and you want to add a description to all objects with a given name, e.g.

- name: alan
  age: 8

- name: britney # some comment about britney
  hobbies: ["painting", "CS"]
  age: 21

- name: charles # some comment about charles
                # that spans over multiple lines
  age: 42

And I have a list of objects with names that require a description, e.g.

britney: teamblue
charles: foobar

How can I add a line with a description to reach the following:

- name: alan
  age: 8

- name: britney # some comment about britney
  hobbies: ["painting", "CS"]
  age: 21
  description: teamblue

- name: charles # some comment about charles
                # that spans over multiple lines
  age: 42
  description: foobar

So far I go pretty close but I keep failing at replacing a multiline plain text with another:

s=$(awk "/${name}/" RS= ./*.yml)
r=$(awk "/${name}/" RS= ./*.yml && echo "  description: ${desc}")

I need to somehow look for $s and replace it with $r and I cannot make it work. I tried multiple variations of the following two:

sed "s/$s/$r/" ./*.yml
perl -i -0pe "s/$s/$r/" ./*.yml

But somehow the special characters (newlines, double quotes, ...) in the yaml break them and I either get an error message like unterminated substitute pattern or the output is the same and nothing was matched.

Also maybe relevant for sed, I'm using macOS.

like image 750
ATN Avatar asked Jul 04 '26 20:07

ATN


1 Answers

$ cat tst.awk
NR==FNR {
    sub(/:/,"",$1)
    map[$1] = $2
    next
}
$3 in map {
    $0 = $0 "\n  description: " map[$3]
}
{ print }

.

$ awk -f tst.awk list RS= ORS='\n\n' foo.yaml
- name: alan
  age: 8

- name: britney # some comment about britney
  hobbies: ["painting", "CS"]
  age: 21
  description: teamblue

- name: charles # some comment about charles
                # that spans over multiple lines
  age: 42
  description: foobar

The above used these input files:

$ cat list
britney: teamblue
charles: foobar

.

$ cat foo.yaml
- name: alan
  age: 8

- name: britney # some comment about britney
  hobbies: ["painting", "CS"]
  age: 21

- name: charles # some comment about charles
                # that spans over multiple lines
  age: 42
like image 193
Ed Morton Avatar answered Jul 11 '26 02:07

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!