在批处理脚本中处理八进制变量(dealing with octal variables in batch script)

编程入门 行业动态 更新时间:2024-10-08 20:34:47
批处理脚本中处理八进制变量(dealing with octal variables in batch script)

嗨我正在运行批处理脚本来获取当前日期并对其执行数值运算。

我通过使用以下命令获取日期,然后对其执行操作(添加,减去等)。

但是如果日期返回的值小于10(例如09,08),则操作会出错。

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

请帮忙

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

最满意答案

你可以用一个小技巧删除零:

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

这将字符串“1”添加到“08”(它仍然是一个字符串),结果为“108”。 然后减去“100”( /a将它们视为数字),结果为“8”。 如果在您的语言环境中日期没有前导零而是空格,则%%d: =0%将其替换为零

如果您需要前导零的结果,只需再次添加:

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

这会在字符串“7”前面添加字符串“0”(之前的结果),得到“07”并从“07”开始取最后两位数(如果之前的结果是“24”, - >添加“0”=“024” - >最后两个=“24”)

编辑也适用于语言环境,其中日期有空格而不是前导零。 (感谢LưuVĩnhPhúc发现它)

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)

更多推荐

本文发布于:2023-07-27 08:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:批处理   变量   脚本   八进制   dealing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!