5

I am trying to increment a build number by 1 using command line.

Here is the content of my test file:

SOME_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 4;
SOME_SECOND_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 4;

The result I want to obtain is the following:

SOME_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 5;
SOME_SECOND_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 5;

I am trying to use something like:

sed -i -E "s/CURRENT_PROJECT_VERSION = (\d+);/CURRENT_PROJECT_VERSION = \1~;/" test.txt

I am not experienced in bash scripting and I don't know how I can increment the number by one. (I am using MacOS but the sed command is almost the same as on Linux)

7
awk -F '= ' '/CURRENT_PROJECT_VERSION/{$2=$2+1";"}1' OFS='= ' input > output

Tests

cat file
SOME_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 4;
SOME_SECOND_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 4;

awk -F '= ' '/CURRENT_PROJECT_VERSION/{$2=$2+1";"}1' OFS='= ' file
SOME_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 5;
SOME_SECOND_DUMMY_VALUE = -1;
CURRENT_PROJECT_VERSION = 5;
  • 1
    I think that only the lines starting with CURRENT_PROJECT_VERSION are to be changed, so you may want to add a $1 == "CURRENT_PROJECT_VERSION" condition to the first rule. – AdminBee Jan 28 at 14:26
  • @AdminBee You are correct. Fixed my answer. – Paulo Tomé Jan 28 at 15:24
  • I think the OFS='= ;' statement is incorrect, look at the ; appearing in front of the incremented build number ... – AdminBee Jan 28 at 15:38
  • @AdminBee Thank you 2 times!! ;) – Paulo Tomé Jan 28 at 15:41
  • All's well that ends well ;) – AdminBee Jan 28 at 15:43
3

Another answer, using only awk. This assumes that you adhere to the key <space> = <space> value; syntax throughout:

awk '$1 == "CURRENT_PROJECT_VERSION" {$3=($3+1)";"}1' testfile.txt

This increases the third field by 1 in all lines starting with CURRENT_PROJECT_NUMBER but otherwise prints all lines "as is" (this is the meaning of the 1 behind the code block).

Note that I'm not sure if the "increment anything starting with a number" syntax is portable, so to be sure (and only slightly longer), we can remove the trailing semicolon from field 3 before incrementing:

awk '$1 == "CURRENT_PROJECT_VERSION" {sub(";","",$3); $3=($3+1)";"}1' testfile.txt
2

With sed and bash:

FILE="test.txt"
REGEX="\(CURRENT_PROJECT_VERSION *= *\)\([0-9]\+\);"

version=$(sed -ne "s/${REGEX}/\2/p" ${FILE} | head -1)
((version++))

sed -ie "s/${REGEX}/\1${version};/" ${FILE}
2

With perl, modifying the file in-place:

perl -pi -e 's/\bCURRENT_PROJECT_VERSION\s*=\s*\K-?\d+/$& + 1/ge' test.txt
  • Or perhaps more readable: 's/\b(CURRENT_PROJECT_VERSION\s*=\s*)(-?\d+)/$1 . ($2+1)/e' – jrw32982 supports Monica Jan 30 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.