Home > Net >  How to change a number in a string using BASH SCRIPT quickly and without a lot of lines of code?
How to change a number in a string using BASH SCRIPT quickly and without a lot of lines of code?

Time:11-03

enter image description here IT IS NECESSARY TO CHANGE ONLY THE VALUE OF THE VERSION IN THIS FILE BY CALLING THE SCRIPT. I only need to change one number on one line of a large config file. That's exactly this version

    version "1.0.0-rc3"    ---->        version "1.0.0-rc4"

cat build.file | grep version | cut -d' ' -f2 | grep -o '[0-9]\ ' | tail -1

I get the version number, I just need to literally increase it by 1 and put it in place of the old one, but I think there is an easier way than I think

CodePudding user response:

sed -E 's/([^0-9]|^)(1.0.0-rc3)([^0-9]|$)/\11.0.0-rc4\3/g' build.file > new.build.file

This sed will replace all instances of 1.0.0-rc3 with 1.0.0-rc4, and won’t clash with anything like 21.0.0-rc3. You can also use sed -i to edit in place, instead of redirection.

edit: as per the comment:

This script will replace all occurrences of 1.0.0-rcN, with an incremented version of the first occurrence.

#!/bin/sh -e

awk \
'match ($0, /([^0-9]|^)1.0.0-rc[0-9] /) {
    if (!rc) {
        rc = substr($0, RSTART, RLENGTH)
        sub(/.*rc/, "", rc)
          rc
    }

    gsub(/([^0-9]|^)1\.0\.0-rc[0-9] /, "1.0.0-rc"rc)
}

{
    print
}' "$1" > "$1".ed
mv "$1".ed "$1"

If the file contains eg both 1.0.0-rc4 and 1.0.0-rc7, in that order, they would both be substituted with 1.0.0-rc5. It uses the first one it finds. If you take out the if statement, it would use the first one it finds on each line. Ie. you get 1.0.0-rc5 and 1.0.0-rc8.

CodePudding user response:

Using awk

awk -F"c" -i inplace '/version/ {$0=$1 $NF   1"\""}1' input_file

This will save the file in place and increment the number at the end.

Output

"version 1.0.0-rc4"
  • Related