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

指南:

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

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

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


当前回答

FIND作为grep的替代品。 我用find给自己黑了个电话簿。非常有用:

@echo off
:begin
set /p term=Enter query: 
type phonebookfile.txt |find /i "%term%"
if %errorlevel% == 0 GOTO :choose
echo No entry found
set /p new_entry=Add new entry: 
echo %new_entry% >> phonebookfile.txt 
:choose
set /p action=(q)uit, (n)ew query or (e)dit? [q] 
if "%action%"=="n" GOTO anfang
if "%action%"=="e" (
    notepad phonebookfile.txt
    goto :choose
)

非常快速有效。

其他回答

There is also the EDLIN command. While it may be an old bastard tool once used for line-based text editing, the fact that it's controllable from the command line makes it rather useful for batch scripting, mostly because, just like any other case you'd be using EDLIN, it's the only tool available. After all, EDLIN is not a tool you would ordinarily want to use for text editing, unless you are somewhat masochistic. To quote Tim Patterson (the fellow who wrote it): "I was aghast when I heard that IBM was using it and not throwing it out the window."

注意:EDLIN将老式的EOF (1A)标记添加到它编辑的文件中。如果需要删除它们,可能必须使用DEBUG。

支持正则表达式的Findstr:

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

我总是发现很难阅读每行用关键字标记的注释:

REM blah blah blah

易于阅读:

:: blah blah blah

递归搜索目录树中的字符串:

findstr /S /C:"string literal" *.*

你也可以使用正则表达式:

findstr /S /R "^ERROR" *.log

递归文件搜索:

dir /S myfile.txt

ENDLOCAL使用的行仍然解析局部变量。这就允许了以下技巧:

ENDLOCAL & SET MYGLOBAL=%SOMELOCAL% & SET MYOTHERGLOBAL=%SOMEOTHERLOCAL%

这是一种将结果传输到调用上下文的有用方法。具体来说,一旦ENDLOCAL完成,% somlocal%就超出了作用域,但那时% somlocal%已经展开,因此MYGLOBAL在调用上下文中使用局部变量赋值。

出于同样的原因,如果你决定这样做:

ENDLOCAL & SET MYLOCAL=%MYLOCAL%

您将发现新的MYLOCAL变量现在实际上是一个常规环境变量,而不是您希望它成为的局部变量。