专业的编程技术博客社区

网站首页 > 博客文章 正文

DOS命令中的空格、数字为何加到8后又变成1?set /a算术运算问题

baijin 2024-08-08 23:02:25 博客文章 74 ℃ 0 评论
  • 8 ≠ 8
  • 12+1 = 11 为何???

空格问题一:当作数字时,没问题。但当作文本字符时事与愿违,会被认为8后面还有一个空格,此时“8 ”不等于“8”

正确写法:赋值时加双引号,set "a=8"

空格问题二:此时不应有 else(echo

原因:dos命令中主要以空格分隔

解决:在else与(之间加一个空格,写成 else (echo即可

空格问题三

重定向时,句柄符与符号间不能有空格,1与>>之间不能有空格

ren "%%i" "!file!!ext!" 1>> batResult.txt 2<&1

空格问题四

findstr 的条件字符集中不能有空格,"[0-9a-z]"正确

空格问题五

  • 赋空值nul,后面不能有空格:set newFile=
  • 判断空值nul(非空格):if not "%newFile%"=="" ()

set /a算术运算问题:12+1=11 ?

目的是让数字自增,并以四位“000n”的形式显示。

以下代码有什么问题

if "%newFExt%"=="" (
	ren "%%i" "!file!!ext!" 1>> batResult.txt 2<&1
	if "!errorlevel!" neq "0" ( echo --原文件"%%i",新文件名"!file!!ext!"-- >>batResult.txt
	) else (set /a a+=1
		if !a!  LSS 10 (set a=000!a!
		) else if !a! LSS 100  (set a=00!a!
		) else if !a! LSS 1000 (set a=0!a!))
) else (ren "%%i" "!file!.%newFExt%" 2>> batResult.txt
	if "!errorlevel!" neq "0" ( echo --原文件"%%i",新文件名"!file!.%newFExt%"-- >>batResult.txt
	) else (set /a a+=1
		if !a!  LSS 10 (set a=000!a!
		) else if !a! LSS 100  (set a=00!a!
		) else if !a! LSS 1000 (set a=0!a!))
)

结果:0001,0002,...,0007,0008,0001,0002,...增加到0008后又变成0001

原因:问题就出在0上,在set命令中0x开头的默认是十六进制、0开头的默认是8进制,08和09是无效的,处理时会认为是0

正确的如下:多加一个用于显示的变量aStr

if "%newFExt%"=="" (
	ren "%%i" "!file!!ext!" 1>> batResult.txt 2<&1
	if "!errorlevel!" neq "0" ( echo --原文件"%%i",新文件名"!file!!ext!"-- >>batResult.txt
	) else (set /a a+=1
		if !a!  LSS 10 (set aStr=000!a!
		) else if !a! LSS 100  (set aStr=00!a!
		) else if !a! LSS 1000 (set aStr=0!a!))
) else (ren "%%i" "!file!.%newFExt%" 2>> batResult.txt
	if "!errorlevel!" neq "0" ( echo --原文件"%%i",新文件名"!file!.%newFExt%"-- >>batResult.txt
	) else (set /a a+=1
		if !a!  LSS 10 (set aStr=000!a!
		) else if !a! LSS 100  (set aStr=00!a!
		) else if !a! LSS 1000 (set aStr=0!a!))
)


类似文章

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表