So I am trying to extract a particular phrase from a properties for in my Shell script for use later on (it will be used as a comment in a Git commit).
The property file, which I will call release.properties, looks something like this:
#Created by build system, do not modify
#Tue Dec 28
git.revision=aaaaa
build.number=1111
app.name=xxxx
app.version=x.y
I want to obtain the string "x.y.1111" from the file above.
My current solution for this is as follows:
input=$(cat release.properties)
arrayIN=(${input//=/ })
length=${#arrayIN[@]}
let length=$length-1
versionComment="${arrayIN[$length]}.${arrayIN[16]}"
Note, index 16 in the array may not be the right one in the example, but it is correct for the actual file I use, it is just supposed to extract the value 1111.
Thus, versionComment will contain the string with the version I want: x.y.1111
However, the problem I am facing is that I have hardcoded the positions where the build.number and app.version information has appeared in the properties file.
Sometimes, when the properties file is generated, the build.number and app.version are not on the same line. It may instead look like:
#Created by build system, do not modify
#Tue Dec 28
build.number=1111
app.name=xxxx
app.version=x.y
git.revision=aaaaa
This of course ruins the version comment.
I was wondering if there is a way to perhaps change all the information in the release.properties file into key-value pairs stored in some object, and then get the appropriate values to create the version comment. But, I am unclear on if such data structures exist for Shell.
Of course, I am open to other solutions as well. Thank you.
CodePudding user response:
I'd write
while IFS="=" read -r prop value; do
case $prop in
"build.number") num=$value ;;
"app.version") ver=$value ;;
esac
done < release.properties
wanted="$ver.$num"
echo "$wanted" # => x.y.1111
CodePudding user response:
Process release.properties
to turn properties into valid shell variable names and dynamically import it into the Bash script, making shellified properties directly available as shell variables.
#!/usr/bin/env bash
# shellcheck disable=SC1090 # dynamically import shellified variables
. <(sed 's/^[^.]*\.//' release.properties)
# shellcheck disable=SC2154 # dynamically imported
printf '%s.%s\n' "$version" "$number"
CodePudding user response:
If build.number
always comes before app.version
then this sed
one-liner should accomplish the task:
sed -n -e '/^build\.number=/{s///;h;}' -e '/^app\.version=/{s///;G;s/\n/./p;q;}' file