Issue
I am looking at replacing some indented lines in a Yaml file using sed.
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
Yaml is strict about its indentation and will want to know how I can accomplish a replacement of the text after example "limits:"
I have tried '0,/cpu:.*m/s//cpu: 900m/'
and '/limits:/!b;n;s//ccpu: 900m'
'0,/cpu:.*m/s//cpu: 900m/'
outputs:
resources:
limits:
cpu: 900m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
The only issue I have with this is I will want to specify the replacement should be done on the example CPU for limits and not for the requests.
So I tried '/limits:/!b;n;s//ccpu: 900m'
which outputs:
resources:
limits:
cpu: 900m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
Notice how it is not properly indented? How can I achieve this by leaving the indentation as it is and also if I can specify 1st and 2nd lines after "limits:" or "requests:" that will be nice.
Solution
If you cannot install yaml parsing tools such as yq
, you can use this gnu-sed
solution:
sed -E '/limits:/!b;n;s/^([[:blank:]]*cpu: ).*/\1900m/' file.yml
resources:
limits:
cpu: 900m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
Breakdown:
/limits:/!b
: Search for textlimits:
otherwise branch to end of scriptn
: Read/append the next line of input into the pattern spaces/.../.../
: Do this substitution^
: Match start([[:blank:]]*cpu: )
: Match 0 or more whitespaces followed by textcpu:
. Capture this in capture group #1.*
: Match remaining text till end of line/\1900m/
: Replace with back-reference of capture group #1 i.e.\1
followed by new value900m
Answered By - anubhava Answer Checked By - Katrina (WPSolving Volunteer)