OS: Windows 10
Tool: git bash
I want to use sed command to change the version string in some files. In git bash, I tried below command and it works.
$ sed -i 's/1.0.0.21/1.0.0.22/g' ../fossa/PluginManifest.xml
Then I put sed command in a script file, like below:
$ cat UpdateVersion.sh
echo $1
echo $2
sed -i 's/$1/$2/g' ../fossa/PluginManifest.xml
And then I execute below command:
$ source UpdateVersion.sh 1.0.0.21 1.0.0.22
1.0.0.21
1.0.0.22
When I check the file, I find the version string is not changed. Why?
CodePudding user response:
In general, any and all input should validated, sanitized, and/or encoded as appropriate before use, especially for input being passed to a command/control interface, such as a shell-executed sed.
In your example, the following may be appropriate (with .s being escaped, as suggested by anubhava and mashuptwice, as unescaped .s instruct the regular expression engine to match any character):
1 if [[ !( $1 =~ ^[0-9.] $ && $2 =~ ^[0-9.] $ ) ]]; then
2 echo "Invalid version syntax" 1>&2
3 exit 1
4 fi
5
6 ver1=${1//./\\.}
7 ver2=${2//./\\.}
8
9 sed -i "s/\b$ver1\b/$ver2/" ../fossa/PluginManifest.xml
Note that, $ver1 is surrounded by \bs to ensure that sed matches on word boundaries (e.g., sed s/1/a/g would match on 1, (1), 12, 21, 121, and 212 (replacing all 1s with a), while sed s/\b1\b/a/g would only match on 1, (1), and other 1s with word boundaries on both sides.
Consider reviewing the manpages for bash and sed, as well as the regular expressions tutorial here: https://www.regular-expressions.info/.
