Astin Gengo
Astin Gengo

Reputation: 405

How to change a text, with sed, when want to match multiple lines

I need to make some changes to a file but want to match multiple lines.

I tried something like sed 's/name-here\n.*version: .*/name-here\nversion: new-version/g' file.yaml but is not working

This is a peace of code from the file

name_here:
- name: name-here
  version: 1.3.2.115
- name: other-name
  version: 1.3.2.115
- name: final-name
  version: 1.3.2.115

After I'll use sed I want to end up with something like:

name_here:
- name: name-here
  version: new-version
- name: other-name
  version: 1.3.2.115
- name: final-name
  version: 1.3.2.115

Upvotes: 2

Views: 74

Answers (3)

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed '/name-here/{:a;n;/version:/s/:.*/: new-version/;Ta}' file

Look for a line containing name-here, then amend the first line containing version:.

If you only want to replace the version: once in a file, use:

sed '/name-here/{:a;n;/version:/s/:.*/: new-version/;Ta;:b;n;bb}' file

Upvotes: 0

Jotne
Jotne

Reputation: 41456

This is an easy job for awk

awk 'f && /version/ {$2="new version";f=0} /name-here/ {f=1} 1'file

name_here:
- name: name-here
version: new version
- name: other-name
  version: 1.3.2.115
- name: final-name
  version: 1.3.2.115

If formatting is important, this should do:

awk 'f && /version/ {sub(/: .*/, ": new version");f=0} /name-here/ {f=1} 1' file
name_here:
- name: name-here
  version: new version
- name: other-name
  version: 1.3.2.115
- name: final-name
  version: 1.3.2.115

Upvotes: 1

Jon
Jon

Reputation: 3671

Because of the structure of the data, you can bodge it using a regular-expression range rather than trying to do multi-line stuff in sed. Really you should do this with a proper YAML tool.

Try

$ sed '/- name: name-here/,/  version:/s/version: .*/version: new-version/' <<END
name_here:
- name: name-here
  version: 1.3.2.115
- name: other-name
  version: 1.3.2.115
- name: final-name
  version: 1.3.2.115
END
name_here:
- name: name-here
  version: new-version
- name: other-name
  version: 1.3.2.115
- name: final-name
  version: 1.3.2.115

Upvotes: 3

Related Questions