Sed requires knowing if there is indeed MONGO_HOST
on that file so grep comes into the solution.
if grep -Fq -- "- name: MONGO_HOST" file.yaml; then
sed 's/^\([[:space:]]\+value:\).*/\1 172.16.87.98/' file.yaml
fi
The if-statement is from the shell, which checks if grep really found a pattern/regexp and execute sed
in this case.
The -F
means grep is looking for fixed strings, not BRE (basic regular expression) nor ERE (extended regular expression)
The -q
means quiet or silence the output.
The --
means end of options, because options usually starts with a dash -
anything after the --
grep will not treat it as an option anymore
If there is/are more than one string value:
with the regexp in that file.yml sed will replace em all. But as suggested already use the proper tool for parsing/editing yaml file.
Edit: as pointed out by Ranvijay Sachan
sed can check if a pattern is there and replace the following line.
Using the command based file editor ed
printf '%s\n' '/MONGO_HOST/+1s/^\([[:space:]]\+value:\).*/\1 172.16.87.98/' ,p w | ed -s file.yaml
yq
. – Fullmouthed