increment variable in a string in shell script

怎甘沉沦 提交于 2019-12-12 06:57:51

问题


I have a string which comes from a variable I want to increment it. how can i do that using shell script?

this is my input which comes from a variable:

abc-ananya-01

output should be:

abc-ananya-02

回答1:


check this:

kent$  echo "abc-ananya-07"|awk -F'-' -v OFS='-' '{$3=sprintf("%02d",++$3)}7' 
abc-ananya-08

The above codes do the increment and keep your number format.




回答2:


It is shorter:

a=abc-lhg-08
echo ${a%-*}-`printf "%02d" $((10#${a##*-}+1))`
abc-lhg-09

Even better:

a=abc-lhg-08
printf "%s-%02d\n" ${a%-*} $((10#${a##*-}+1))
abc-lhg-09



回答3:


Bash string manipulations can be used here.

a='abc-ananya-07'
let last=$(echo ${a##*-}+1)
echo ${a%-*}-$(printf "%02d" $last)




回答4:


With pure Bash it is a bit long:

IFS="-" read -r -a arr <<< "abc-ananya-01"
last=10#${arr[${#arr}-1]}    # to prevent getting 08, when Bash 
                             # understands it is a number in base 8
last=$(( last + 1 ))
arr[${#arr}-1]=$(printf "%02d" $last)
( IFS="-"; echo "${arr[*]}" )

This reads into an array, increments the last element and prints it back.

It returns:

abc-ananya-02


来源:https://stackoverflow.com/questions/36933682/increment-variable-in-a-string-in-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!