Increment variable in line in shell script

I have a line that comes from a variable I want to increase it. how can i do this with a shell script?

this is my input that comes from a variable:

abc-ananya-01 

the conclusion should be:

 abc-ananya-02 
-one
bash sh
source share
4 answers

check this:

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

The above codes make an increase and save your number format.

+1
source share

In short:

 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
source share

With pure Bash, it's a little 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[*]}" ) 

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

It returns:

 abc-ananya-02 
+1
source share

Bash String manipulation can be used here.

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

enter image description here

+1
source share

All Articles