Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

dealing with octal variables in batch script

Hi I am running a batch script to get a current date and perform numerical operations on it.

I get the date by using the following command and then do operations on it (Add, Subtract etc).

But If the date returns a value less than 10 (eg. 09, 08) the operation gives an error.

set dd=%date:~7,2%   
set /a dd1=08-1 
Invalid number.  Numeric constants are either decimal (17),hexadecimal (0x11), or octal (021).

Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can remove the zero with a little trick:

set /a dd1=(1%dd: =0%-100)-1

This adds the string "1" to "08" (which is also still a string), resulting in "108". Then subtract "100" (/a treating them as numbers), which results in "8". If in your locale the date has no leading zero but a space instead, %%d: =0% replaces it with a zero

If you need the result with leading zero, just add it again:

set dd1=0%dd1%
set dd1=%dd1:~-2%

This adds the string "0" in front of the string "7" (result from before), resulting in "07" and takes the last two digits from it "07" (in case, the result from before is "24", -> add "0" = "024" -> last two = "24")

edited to work also in locales, where the date has a space instead of a leading zero. (thanks to L?u V?nh Phúc for spotting it)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...