To use sed
, for the scenario that you describe, with an input file like this:
master_green_cloud_init_version = "v1.16/"
master_blue_cloud_init_version = "v1.16/"
This script*
#!/bin/sh
userdata_version=v2.21
sed -i -e "/master_green_cloud_init_version/s/".*"/"${userdata_version}"/" input.txt
results in
$ more input.txt
master_green_cloud_init_version = "v2.21"
master_blue_cloud_init_version = "v1.16/"
$
Note that you need double quotes for the sed
expression, in order to use the shell variable, see this answer to Shell variables in sed script.
Then you also need to escape the double quotes that you are searching for, using \"
. You will need to do this twice, once for the starting double quote and once for the end.
The -i
works on the input file rather than just outputting the result to stdout
.
Note: If, for some reason, you want to keep the forward slash at the end of the version string, then use an escaped forward slash (\/
), like so:
#!/bin/sh
userdata_version=v2.21
sed -e "/master_green_cloud_init_version/s/".*/"/"${userdata_version}/"/" input.txt
which, for the same input file, gives
master_green_cloud_init_version = "v2.21/"
master_blue_cloud_init_version = "v1.16/"
* From How to use sed to find and replace text in files in Linux / Unix shell:
How to use sed to match word and perform find and replace
In this example only find word ‘love’ and replace it with ‘sick’ if
line content a specific string such as FOO:
sed -i -e '/FOO/s/love/sick/' input.txt
See also How can I replace a string in a file(s)?
sed
in single quotes? – ctrl-alt-delor Aug 24 '21 at 22:28