Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment a number at the end of a string in bash?

Tags:

bash

Basically i need to create a function where an argument is passed, and i need to update the number so for example the argument would be

version_2 and after the function it would change it to version_3

just increments by one

in java I would just create a new string, and grab the last character update by one and append but not sure how to do it in bash.

updateVersion() {
  version=$1
}

the prefix can be anything for example it can be dog12 or dog_12 and always has one number to update.

after the update it would be dog13 or dog_13 respectively.

like image 480
DDisciple Avatar asked Apr 17 '19 15:04

DDisciple


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does %% mean in bash?

The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching. Follow this answer to receive notifications.

What does %s do in bash?

According to this resource , when used with the printf command, “%s” Interprets the associated argument literally as string. How does shell (bash) in Linux work? I think shell is an interface which takes the commands we type in the terminal and searches the inbuilt command in bin and executes the output.


2 Answers

updateVersion()
{
    [[ $1 =~ ([^0-9]*)([0-9]+) ]] || { echo 'invalid input'; exit; }     
    echo "${BASH_REMATCH[1]}$(( ${BASH_REMATCH[2]} + 1 ))"
}

# Usage
updateVersion version_11         # output: version_12
updateVersion version11          # output: version12
updateVersion something_else123  # output: something_else124
updateVersion "with spaces 99"   # output: with spaces 100

# Putting it in a variable
v2="$(updateVersion version2)"
echo "$v2"                       # output: version3
like image 135
Anubis Avatar answered Nov 15 '22 06:11

Anubis


Use parameter expansion:

#! /bin/bash
shopt -s extglob
for version in version_1 version_19 version_34.14 ; do
    echo $version
    v=${version##*[^0-9]}
    ((++v))
    echo ${version%%+([0-9])}$v
done

extglob is needed for the +([0-9]) construct which means "one or more digits".

like image 35
choroba Avatar answered Nov 15 '22 05:11

choroba