Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing Shell script that can account for changing positions of lines in a file

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading