DOS命令编程

示例

1. echo off

  • When echo is turned off, the command prompt doesn't appear in the Command Prompt window. To display the command prompt again, type echo on.
  • @echo off在批处理文件第一行,在整个bat 文件中生效
@echo off
rem HelloWorld.bat,this line need after @echo off to avoid show
set x = hello world
echo %x%

结果显示

>HelloWorld.bat
hello world

2. for

  • %%variable双百分号表示变量,变量名区分大小写不同于windows下文件名
  • FOR %variable IN (set) DO command [command-parameters]
    简单示例
@echo off
rem example 1
for %%i in (*.bat) do @echo %%i

for 扩展命令

  • 指定与目录名匹配,而不与文件名匹配
    FOR /D %variable IN (set) DO command [command-parameters]
  • 以 [drive:]path 为根的目录树,指向每个目录
    FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
  • 以增量形式从开始到结束的一个数字序列
    FOR /L %variable IN (start,step,end) DO command [command-parameters]
    因此,(1,1,5) 将产生序列 1 2 3 4 5,(5,-1,1) 将产生
    序列 (5 4 3 2 1)。
@echo off
for /L %%i in (1,1,5) do @echo %%i

>test_for_l.bat
1
2
3
4
5
  • 遍历文件 /F
    FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
    FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
    FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
@echo off
FOR /F "eol=; tokens=1,2,* delims=," %%i in (test_for_f.txt) do @echo %%i %%j %%k

line2 bb
line3 cc dd

test_for_f.txt内容
;line1,aa
line2,bb
line3,cc,dd
  • eol=c - 指一个行注释字符的结尾(就一个)
  • skip=n - 指在文件开始时忽略的行数。
  • delims=xxx - 指分隔符集。这个替换了空格和跳格键的默认分隔符集。
  • tokens=x,y,m-n - 指每行的哪一个符号被传递到每个迭代的 for 本身

参考资料

  • Windows commands
    https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands
  • 常用DOS网络命令
    https://www.cnblogs.com/liuzhengliang/p/8617083.html

你可能感兴趣的:(DOS命令编程)