简体   繁体   中英

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.

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}")

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}")

You can do somewhat the same thing with parameter expansion with substring substitution , eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM