I manage the build process for Android applications. Part of the process automatically updates the version of the application in various build.gradle files. In a Jenkinsfile, a list of file paths are passed into a for-loop in which the find-and-replace sed command is run to set the new version number.
Sed for Find-and-Replace
Sed is a library used for performing all sorts of text operations, which makes it very handy for scripting related work.
The command for find and replace is simple to use. If you have a file called “animals.txt” and you want to replace all instances of “cat” with “dog”, you would use:
# replace all occurrences of 'cat' with 'dog' in animals.txt
sed -i 's/cat/dog/g' animals.txt
A real world example
Here is part of the script that updates the Android versions for me. The sed command searches for the phrase ":1.0@aar" and replaces it with ":$insertVersion@aar", where $insertVersion is a variable that holds the new version number. This command is run on each one of our build.gradle files.
The cat command then prints the contents of the build.gradle files in case they are needed for troubleshooting later.
for (dependency in dependencyMap) {
for (entry in dependency.gradleEntry) {
print "Updating library dependency for $dependency.path, $entry"
print "dependency version: $insertVersion"
sh """
#!/bin/bash
# replace 1.0 with versionCode
sed -i 's/:1.0@aar/:$insertVersion@aar/g' ${dependency.path}/build.gradle
cat ${dependency.path}/build.gradle
"""
}
}