I am trying to replace the value of a variable "Tag" next to the searched pattern, like:
If name in images is "repo.url/app1" Replace Tag: NEW_VALUE
Below is the yaml sample file where I need to replace the values.
namespace: dev
resources:
- file.yaml
- ../../..
images:
- name: repo.url/app1
Tag: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- name: repo.url/app2
Tag: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
So far I tried
sed -i "/\-\ name\:\ repo.url\/app1/{n;n;s/\(Tag\).*/\1: $NEW_VALUE/}" file
which doesn't do anything and doesn't throw any error. I am not sure, if there's a better way to handle such substitutions.
CodePudding user response:
Simplest way with sed
is just to match the line and then perform the substitution on the next (\w
used to match all word-characters at the end of the line for replacement), e.g.
sed -E '/repo\.url\/app1$/{n;s/\w $/yyyyyyyyyyyyyyyyyyyyyy/}' file.yaml
Example Use/Output
sed -E '/repo\.url\/app1$/{n;s/\w $/yyyyyyyyyyyyyyyyyyyyyy/}' file.yaml
namespace: dev
resources:
- file.yaml
- ../../..
images:
- name: repo.url/app1
Tag: yyyyyyyyyyyyyyyyyyyyyy
- name: repo.url/app2
Tag: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Using awk
Another way is to use awk
and a flag to indicate replace in next line (rep
below). Then use sub()
to replace the 'x'
s with whatever you need, e.g.
awk '
rep { sub(/\w $/,"yyyyyyyyyyyyyyyyyyyyyyyy"); rep = 0 }
$NF == "repo.url/app1" { rep=1 }
1
' file.yaml
Where 1
is just shorthand for print current record.
Example Use/Output
awk 'rep { sub(/\w $/,"yyyyyyyyyyyyyyyyyyyyyyyy"); rep = 0 } $NF == "repo.url/app1" { rep=1 }1' file.yaml
namespace: dev
resources:
- file.yaml
- ../../..
images:
- name: repo.url/app1
Tag: yyyyyyyyyyyyyyyyyyyyyyyy
- name: repo.url/app2
Tag: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Just redirect the output to a new file to save, e.g. awk '{...}' file.yaml > newfile.yaml
.