简体   繁体   English

更改变量中的数字

[英]Change a Number inside a Variable

I have the following problem: (Its about dates) The user will set the following variable. 我有以下问题:(关于日期)用户将设置以下变量。

variable1=33_2016 variable1 = 33_2016

now I Somehow want to to automatically set a second variable which sets the "33" +1 that I get 现在我以某种方式想要自动设置第二个变量,该变量设置我得到的“ 33” +1

variable2=34_2016 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. 我的第一选择是将第一个变量与read分开,然后将(更新的)片段放在一起。

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). 您还可以使用一个正则表达式,该正则表达式在解析时更易读,但是将它们放回原处的时间更长( BASH_REMATCH可以使用较短的同义词)。

[[ $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

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. 这是六比一, 半打到另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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