Avatar of welcome 123
welcome 123
 asked on

How to add variable string in unix

I have string A which has value dynamical comming form database.
I want to add that string + 1 and get the output.

For example:
A=05
I want add this variable +1.
B=$A+1
and desired outpu should be 05+1= 06.
Output should be 06.

Note I am using ksh script.

Can you please reply as soon as possible.

Thanks,
Sailaja.
Unix OS

Avatar of undefined
Last Comment
woolmilkporc

8/22/2022 - Mon
welcome 123

ASKER
I beleve dc operator can be used.
welcome 123

ASKER
I am geting the result as 6 I want the result as 06 how we get that.

BD0_MON=05
val=`expr $BD0_MON + 1`
6
desired output 06
woolmilkporc

B=$(echo $A | awk '{printf "%02d", $1+1}')

Or like this:

B=$(awk -v A="$A" 'BEGIN {printf "%02d", A+1}')

Under bash this works as well:

B=$(awk '{printf "%02d", $1+1}' <<<$A)
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
woolmilkporc

If it's for calculating months so that you want 12 + 1 to become 01 try this:

B=$(echo $A | awk '{printf "%02d", ($1+1)%12}')

B=$(awk '{printf "%02d", ($1+1)%12}' <<<$A)  # BASH

B=$(awk -v A="$A" 'BEGIN {printf "%02d", (A+1)%12}')
SOLUTION
ozo

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
woolmilkporc

Sorry, ozo, my arithmetic skills are indeed quite rusty, but I can't see the difference.

Example "7":

My version: 7 + 1 gives 8. Dividing 8 by 12  gives remainder 8.

Your version: Dividing 7 by 12 gives remainder 7. 7 + 1 gives 8.

Example "12":

My version:  12 + 1 gives 13. Dividing 13 by 12 gives remainder 1.

Your version: Dividing 12 by 12 gives remainder 0. 0 + 1 gives 1.


(m+1)%n = m%n+1

OK, your version saves a pair of parentheses.

Confused:

wmp
ozo

Example, "11"
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
woolmilkporc

I saw that coming  ...

Thanks for the lesson!

wmp
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.