tso
tso

Reputation: 317

Change a Number inside a Variable

I have the following problem: (Its about dates) The user will set the following variable.

variable1=33_2016

now I Somehow want to to automatically set a second variable which sets the "33" +1 that I get

variable2=34_2016

Thanks for any advice.

Upvotes: 0

Views: 56

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84642

You can do somewhat the same thing with parameter expansion with substring substitution, e.g.

$ v1=33_2016
$ v2=${v1/${v1%_*}/$((${v1%_*}+1))}
$ echo $v2
34_2016

It's six to one, a half-dozen to another.

Upvotes: 0

chepner
chepner

Reputation: 532313

My first choice would be to break the first variable apart with read, then put the (updated) pieces back together.

IFS=_ read f1 f2 <<< "$variable1"
# Option 1
variable2=$((f1 + 1))_$f2
# Option 2
printf -v variable2 '%s_%s" "$((f1 + 1))" "$f2"

You can also use parameter expansion to do the parsing:

f1=${variable%_*}
f2=${variable#*_}

You can also use a regular expression, which is more readable for parsing but much longer to put the pieces back together (BASH_REMATCH could use a shorter synonym).

[[ $variable1 =~ (.*)_(.*) ]] && 
  f1=$((${BASH_REMATCH[1]}+1)) f2=${BASH_REMATCH[2]}

The first and third options also allow the possibility of working with an array:

# With read -a
IFS=_ read -a f <<< "$variable1"
variable2=$(IFS=_; echo "${f[*]}")

# With regular expression
[[ $variable1 =~ (.*)_(.*) ]]
variable2=$(IFS=_; echo "${BASH_REMATCH[*]:1:2}")

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158230

You can use awk:

awk 'BEGIN{FS=OFS="_"}{$1+=1}1' <<< "${variable1}"

While this needs an external process to spawn (a bit slower) it's easier to read/write. Decide for yourself what is more important for you here.

To store the return value in a variable, use command substitution:

variable2=$(awk 'BEGIN{FS=OFS="_"}{$1+=1}1' <<< "${variable1}")

Upvotes: 0

Related Questions