Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?

指南:

每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包

澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。

(请参见:Windows批处理文件:.bat vs .cmd?)


当前回答

支持正则表达式的Findstr:

findstr "^[0-9].*" c:\windows\system32\drivers\etc\hosts

其他回答

子字符串变量:

> set str=0123456789
> echo %str:~0,5%
01234
> echo %str:~-5,5%
56789
> echo %str:~3,-3%
3456

能够运行命令并处理输出(如bash中的'$()'的反引号)。

for /f %i in ('dir /on /b *.jpg') do echo --^> %i

如果文件名中有空格,可以这样写:

for /f "tokens=*" %i in ('dir /on /b *.jpg') do echo --^> %i

为了从脚本内部解析stdin,你需要使用For和FIND命令:

for /f "tokens=*" %%g in ('find /V ""') do (
     :: do what you want with %%g
     echo %%g
)

通过使用CALL, EXIT /B, SETLOCAL和ENDLOCAL可以实现带有局部变量的子例程。

例子:

@echo off

set x=xxxxx
call :sub 10
echo %x%
exit /b

:sub
setlocal
set /a x=%1 + 1
echo %x%
endlocal
exit /b

这将打印

11
xxxxx

尽管:sub修改了x。

输出一个空行:

echo.