Batch Usage


Batch Usage
2010年07月13日
  PART I Basic
  -------------------------------------------------- --------------------------------------------
  Lesson 1. ECHO and Environment variables
  (1)Displaying text:
  > echo text
  (2)Turn off ECHO to stop script lines echoing,
  Use the @  prefix to turn off echo of a single line
  > @echo off
  (3)Extension: .bat,Registered in HKEY_CLASSES_ROOT,
  (4)Conflict,use period.to remove it: 
  > echo.off
  Others: Comma   ;   =   :  and  Period    /   \   +   [   ]    " .
  (5)Expanding a variable, %src% 
  (6)Global variables
  winbootdir:        The path to your windows folder
  COMSPEC:        The path to COMMAND.COM,C:\WINDOWS\SYSTEM32\CMD.EXE
  PATH:            Windows searches to run a program,C:\WINDOWS;C:\WINDOWS\SYSTEM32
  TEMP:            The path to the temporary folder,C:\WINDOWS\TEMP
  PROMPT:            This specifies how the prompt looks.set to $p$g. The $p means display current 
  drive and path to current folder, and $g means display a > symbol.
  windir:            The path to your windows folder,C:\WINDOWS
  CMDLINE:        Holds the last command line used for an external command.
  > echo %TEMP%
  (7)Clear variable,no trailing space
  > set task=
  Lesson 2   Using Child Shells
  (1)Opening a child shell,suppress version info with the /k(stands for Keep)
  >command
  (2)Return Code:
  * 0 (zero)Program reports everything OK (or simply nothing to report)
  * 1 (and other small values)useful items of information (specific to Program)
  * 250 - 255Program reports error conditions or warnings
  open a command shell with the switch /z, Windows reports each time the return-code is reset;
  /w switch makes the script wait for the return code;
  /c opens a Single-use child shell for one command line only, 
  and closes it automatically
  (3)Debug-mode shell
  /y switch of command turns on single-step debug mode.
  Lesson 3 Using choice and ERRORLEVELs
  Lesson 4 Finding the current ERRORLEVEL: 
  Lesson 5 Scripts as Useful Intermediate Tools
  (1)Comments
  # ::  (double colon) the line is ignored by Windows (this is better for comments)
  # REM  most (not all) commands that follow are ignored (best kept for special use)
  (2)Labels
  GOTO,begins with a single:(colon),unique over their first eight characters,
  ::JOBDONE
  ::CLEANUP
  ::EOF
  Lesson 6 Designing Menus in Batch scripts
  (1)Folder dot aliases
  * . is shorthand for the current folder
  * .. is shorthand for the parent of the current folder
  (2)Printing the screen: Shift + PrintScrn
  (3)Redirection
  STDOUT output to various devices:
  * CON   the DVM screen (and the default STDOUT device)   
  * NUL   ECHO.Message>NUL sends the message into oblivion (suppresses it)
  * PRN   ECHO.Message>PRN sends the message to the default printer (prints it)
  * COM1   ECHO.ath1>COM1 sends the message to the first serial port,
  if you have a modem connected there, and it's not in use:
  o ath1 should set it off hook (pick up and get a dialling tone)
  o ath0 should restore the on hook condition (hang up again)
  operator >  creates a new file. If a file with the same name already exists, it's deleted and replaced with the new file;
  operator >> append text to an existing file,
  (4)Display file content
  > type file
  (5)emending suffix  .\ 
  To solve the suffix \ problem
  dir C:\CSW\TMP\.\s.txt /b
  Lesson 8 Managing Workfiles and Debugging Batch scripts
  (1)Using wildcards with COPY
  > copy *.txt "c:\bktest\text files\*.DAT"
  (2)Removing an existing folder and contents
  > rd c:\test
  > deltree c:\test
  /y switch of COPY to reply  Y   
  Lesson 9 Copying and concatenating files
  (1)\*.* flags BKTEST as a folder, not a file
  (2)copy /b switch ensures the files are copied normally
  > copy /b j?.txt carroll2.txt
  (3)An easy way to compare files, fc (file compare)
  > fc carroll.txt carroll2.txt
  (4)Use COPY with  + , or a wildcard
  Lesson 10 Testing for existence of files or folders
  (1) IF  EXIST test (fails for folders)
  > if exist a.txt echo.Yes, it exists
  (2) wildcard *.*  represents any file with any extension. 
  We can use it to test whether or not any file at all exists in a folder.
  > if exist a\*.* echo.Yes, it exists
  Lesson 11 Finish Coding the Setup Batch script
  /a-d switch combination of DIR, to list files only
  Lesson 12  Command-line Parameters and String Comparison
  (1)special parameter symbols
  %1   this is expanded to the text in the first item after the script name
  %2   this is expanded to the text in the second item after the script name
  ...
  %10     is expanded as simply %1 + a literal zero          c:\mydocs0
  (2)Conditional comparisons IF Text==Text (space is ignored)
  > IF Text==Text echo.yes
  (3)Add some text to both sides of the comparison, in case of empty
  > if not (%part1%)==() set src=%part1%
  (4)Displaying  %  literally: %%
  Lesson 13 Plan and Menu Logic of Backup script
  (1)FOR command
  1. repeating a command for all the items in a simple list
  2. repeating a command for all the files that fit a wildcard specification
  example, *.TXT   all the files in the current folder that have the extension .TXT)
  FOR  1  IN  2  DO  3 
  *  1  We decide on an index variable that will be used to range over the list. 
  The format of the index variable is a  %  followed by a letter, for example %v
  *  2  We put the list in parentheses, like this: (one two three). 
  The index variable will then behave as if it is each one of these in turn.
  *  3  We add a command to be repeated for each item in the list. 
  Everywhere we want that item to come in the command, we put the index variable, %v
  > for %v in (one two three) do echo.%v
  (2)FOR   script syntax
  (1) use lowercase in immediate mode, and, as usual for internal commands, uppercase in scripts
  (2) The syntax of the FOR command in scripts,
  must specify the index variable with two leading  %%  characters to avoid a syntax error;
  (3) syntax
  syntax error message, or other problem, check:
  * all of the elements FOR IN DO are included in their correct positions
  * double  %%  is used in both places that  %%V  occurs
  * The  V  is capitalised in both instances of  %%V  
  (you can use another letter, but it must be the same letter, and in the same case, in both places)
  (4) learns
  * Use mixed-case labels to remind us the first 8  characters must be unique
  * Use commented labels to create the initial outline of a complex script
  * Use the FOR IN DO command to carry out simple repetitive jobs
  Lesson 14   Understanding File Backup methods
  (1)Finding the right files
  Date stamp,Archive attribute
  (2)dot alias
  DIR's /a-d switch to suppress them
  (3)Filtering with find
  use find to filter text for lines containing a target string.
  > find /i "sea" note
  :  (colon) character occurs in most relevant lines in a DIR listing
  (4)Backup the file (xcopy)
  xcopy has more switch options, and (unlike COPY) will create the target folder 
  if it doesn't exist already;
  > xcopy src\*.* SRCBK\*.* /y
  /d, a source file is not copied unless it is more up-to-date than any same-named file in the destination folder..
  Lesson 15  Coding Backup option and a Drive-Ready test
  (1)Testing whether the destination drive is ready
  > xcopy %DEST%\NUL
  (2)ERRORLEVEL test
  > xcopy %DEST%\NUL GOTO E_SETUP
  Comparation: String use ==, other no operator;
  xcopy C:\BKTEST\nul /l>nul         ERRORLEVEL
  if drive not ready     4
  if drive is ready but folder doesn't exist     1
  if drive is ready     0
  Lesson 16 Using the Pipe operator
  (1)pipe operator |  to join the STDOUT (output channel) of DIR to the STDIN (input channel) of find
  * Windows creates a file (in the TEMP folder) containing the output of TYPE
  * This temporary file is sent to the find command as its input
  * The temporary file is deleted by Windows as the command line finishes
  Lesson 17 Synchronizing a Backup, and more Pipe work
  (2)Jump on exact value
  > IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 GOTO SYNCHYES
  The first part tests that the reply code was greater than or equal to 1. 
  Then, if it was, the second stage goes on to test it was also NOT greater than or equal to 2.
  Lesson 18 Coding the Check and Restore options
  > xcopy /l 
  List only,not real copy
  Lesson 19 Finishing the Backup script project
  Lesson 20 Further Batch skills and Practice
  (1) attrib command to set the hidden attribute of CARROLL.TXT 
  > attrib +h carrot.txt
  (2)Long file names from FOR with LFNFOR
  (3)Batch command line in Windows 95/98/ME has a maximum limit of 64  ?  tokens. 
  # SHIFT to shift the point of view of the %0 to %9  symbols used to access the command-line. 
  We'll make DEMO.BAT  "loop through" its parameters
  # CALL to call (=run) one batch script from another, and return to the original script after 
  the called script has finished
  -------------------------------------------------- --------------------------------------------------- ---------
  PART II COMMANDS
  1 echo 和 @
  @                      #关闭单行回显
  echo off               #从下一行开始关闭回显
  @echo off              #从本行开始关闭回显。一般批处理第一行都是这个
  echo on                #从下一行开始打开回显
  echo                   #显示当前是 echo off 状态还是 echo on 状态
  echo.                  #输出一个"回车换行",空白行
  #(同echo, echo; echo+ echo[ echo] echo/ echo")
  2 errorlevel
  echo %errorlevel%
  每个命令运行结束,可以用这个命令行格式查看返回码
  默认值为0,一般命令执行出错会设 errorlevel 为1
  3 dir
  dir                   #显示当前目录中的文件和子目录
  dir /a                #显示当前目录中的文件和子目录,包括隐藏文件和系统文件
  dir c: /a:d           #显示 C 盘当前目录中的目录
  dir c: /a:-d          #显示 C 盘根目录中的文件
  dir c:" /b/p          #/b只显示文件名,/p分页显示
  dir *.exe /s          #显示当前目录和子目录里所有的.exe文件
  4 cd
  cd"                   #进入根目录
  cd                    #显示当前目录
  cd /d d:"sdk          #可以同时更改盘符和目录
  5 md
  md d:"a"b"c           #如果 d:"a 不存在,将会自动创建中级目录
  #如果命令扩展名被停用,则需要键入 mkdir "a"b"c。
  6 rd
  rd abc                #删除当前目录里的 abc 子目录,要求为空目录
  rd /s/q d:"temp       #删除 d:"temp 文件夹及其子文件夹和文件,/q安静模式
  7 del
  del d:"test.txt       #删除指定文件,不能是隐藏、系统、只读文件
  del /q/a/f d:"temp"*.*
  删除 d:"temp 文件夹里面的所有文件,包括隐藏、只读、系统文件,不包括子目录
  del /q/a/f/s d:"temp"*.*
  删除 d:"temp 及子文件夹里面的所有文件,包括隐藏、只读、系统文件,不包括子目录
  8 ren
  ren d:"temp tmp       #支持对文件夹的重命名
  9 cls
  清屏
  10 type
  显示文件内容
  type c:"boot.ini      #显示指定文件的内容,程序文件一般会显示乱码
  type *.txt            #显示当前目录里所有.txt文件的内容
  11 copy
  拷贝文件
  copy c:"test.txt d:"test.bak
  复制 c:"test.txt 文件到 d:" ,并重命名为 test.bak
  copy con test.txt
  从屏幕上等待输入,按 Ctrl+Z 结束输入,输入内容存为test.txt文件
  con代表屏幕,prn代表打印机,nul代表空设备
  copy 1.txt + 2.txt 3.txt
  合并 1.txt 和 2.txt 的内容,保存为 3.txt 文件
  如果不指定 3.txt ,则保存到 1.txt
  copy test.txt +
  复制文件到自己,实际上是修改了文件日期
  12 title
  设置cmd窗口的标题
  title 新标题          #可以看到cmd窗口的标题栏变了
  13 ver
  显示系统版本
  14 label 和 vol
  设置卷标
  vol                   #显示卷标
  label                 #显示卷标,同时提示输入新卷标
  label c:system        #设置C盘的卷标为 system
  15 pause
  暂停命令
  16 rem 和 ::
  注释命令
  注释行不执行操作
  17 date 和 time
  日期和时间
  date            #显示当前日期,并提示输入新日期,按""回车""略过输入
  date/t          #只显示当前日期,不提示输入新日期
  time            #显示当前时间,并提示输入新时间,按""回车""略过输入
  time/t          #只显示当前时间,不提示输入新时间
  18 goto 和 :
  跳转命令
  :label          #行首为:表示该行是标签行,标签行不执行操作
  goto label      #跳转到指定的标签那一行
  19 find (外部命令)
  查找命令
  find ""abc"" c:"test.txt
  在 c:"test.txt 文件里查找含 abc 字符串的行
  如果找不到,将设 errorlevel 返回码为1
  find /i "abc" c:"test.txt
  查找含 abc 的行,忽略大小写
  find /c ""abc"" c:"test.txt
  显示含 abc 的行的行数
  20 more (外部命令)
  逐屏显示
  more c:"test.txt      #逐屏显示 c:"test.txt 的文件内容
  21 tree
  显示目录结构
  tree d:"              #显示D盘的文件目录结构
  22 &
  顺序执行多条命令,而不管命令是否执行成功
  23 &&
  顺序执行多条命令,当碰到执行出错的命令后将不执行后面的命令
  find ""ok"" c:"test.txt && echo 成功
  如果找到了""ok""字样,就显示""成功"",找不到就不显示
  24 ||
  顺序执行多条命令,当碰到执行正确的命令后将不执行后面的命令
  find ""ok"" c:"test.txt || echo 不成功
  如果找不到""ok""字样,就显示""不成功"",找到了就不显示
  25 |
  管道命令
  dir *.* /s/a | find /c "".exe""
  管道命令表示先执行 dir 命令,对其输出的结果执行后面的 find 命令
  该命令行结果:输出当前文件夹及所有子文件夹里的.exe文件的个数
  type c:"test.txt|more
  这个和 more c:"test.txt 的效果是一样的
  26 > 和 >>
  输出重定向命令
  > 清除文件中原有的内容后再写入
  >> 追加内容到文件末尾,而不会清除原有的内容
  主要将本来显示在屏幕上的内容输出到指定文件中
  指定文件如果不存在,则自动生成该文件
  type c:"test.txt >prn
  屏幕上不显示文件内容,转向输出到打印机
  echo hello world>con
  在屏幕上显示hello world,实际上所有输出都是默认 >con 的
  copy c:"test.txt f: >nul
  拷贝文件,并且不显示""文件复制成功""的提示信息,但如果f盘不存在,还是会显示出错信息
  copy c:"test.txt f: >nul 2>nul
  不显示"文件复制成功"的提示信息,并且f盘不存在的话,也不显示错误提示信息
  echo ^^W ^> ^W>c:"test.txt
  生成的文件内容为 ^W > W
  ^ 和 > 是控制命令,要把它们输出到文件,必须在前面加个 ^ 符号
  27 temp.txt
  date 删除引号(""),扩充 %1
  %~f1          - 将 %1 扩充到一个完全合格的路径名
  %~d1          - 仅将 %1 扩充到一个驱动器号
  %~p1          - 仅将 %1 扩充到一个路径
  %~n1          - 仅将 %1 扩充到一个文件名
  %~x1          - 仅将 %1 扩充到一个文件扩展名
  %~s1          - 扩充的路径指含有短名
  %~a1          - 将 %1 扩充到文件属性
  %~t1          - 将 %1 扩充到文件的日期/时间
  %~z1          - 将 %1 扩充到文件的大小
  %~$PATH : 1 - 查找列在 PATH 环境变量的目录,并将 %1
  扩充到找到的第一个完全合格的名称。如果环境
  变量名未被定义,或者没有找到文件,此组合键会
  扩充到空字符串
  可以组合修定符来取得多重结果:
  %~dp1         - 只将 %1 扩展到驱动器号和路径
  %~nx1         - 只将 %1 扩展到文件名和扩展名
  %~dp$PATH:1 - 在列在 PATH 环境变量中的目录里查找 %1,
  并扩展到找到的第一个文件的驱动器号和路径。
  %~ftza1       - 将 %1 扩展到类似 DIR 的输出行。
  可以参照 call/? 或 for/? 看出每个参数的含意
  echo load ""%%1"" ""%%2"">c:"test.txt
  生成的文件内容为 load ""%1"" ""%2""
  批处理文件里,用这个格式把命令行参数输出到文件
  29 if
  判断命令
  if ""%1""==""/a"" echo 第一个参数是/a
  if /i ""%1"" equ ""/a"" echo 第一个参数是/a
  /i 表示不区分大小写,equ 和 == 是一样的,其它运算符参见 if/?
  if exist c:"test.bat echo 存在c:"test.bat文件
  if not exist c:"windows (
  echo 不存在c:"windows文件夹
  )
  if exist c:"test.bat (
  echo 存在c:"test.bat
  ) else (
  echo 不存在c:"test.bat
  )
  30 setlocal 和 endlocal
  设置"命令扩展名"和"延缓环境变量扩充"
  SETLOCAL ENABLEEXTENSIONS              #启用""命令扩展名""
  SETLOCAL DISABLEEXTENSIONS             #停用""命令扩展名""
  SETLOCAL ENABLEDELAYEDEXPANSION        #启用""延缓环境变量扩充""
  SETLOCAL DISABLEDELAYEDEXPANSION       #停用""延缓环境变量扩充""
  ENDLOCAL                               #恢复到使用SETLOCAL语句以前的状态
  "命令扩展名"默认为启用
  "延缓环境变量扩充"默认为停用
  批处理结束系统会自动恢复默认值
  可以修改注册表以禁用""命令扩展名"",详见 cmd /? 。所以用到""命令扩展名""的程
  序,建议在开头和结尾加上 SETLOCAL ENABLEEXTENSIONS 和 ENDLOCAL 语句,以确
  保程序能在其它系统上正确运行
  ""延缓环境变量扩充""主要用于 if 和 for 的符合语句,在 set 的说明里有其实用例程
  31 set
  设置变量
  引用变量可在变量名前后加 % ,即 %变量名%
  set                      #显示目前所有可用的变量,包括系统变量和自定义的变量
  echo %SystemDrive%       #显示系统盘盘符。系统变量可以直接引用
  set p                    #显示所有以p开头的变量,要是一个也没有就设errorlevel=1
  set p=aa1bb1aa2bb2       #设置变量p,并赋值为 = 后面的字符串,即aa1bb1aa2bb2
  echo %p%                 #显示变量p代表的字符串,即aa1bb1aa2bb2
  echo %p:~6%              #显示变量p中第6个字符以后的所有字符,即aa2bb2
  echo %p:~6,3%            #显示第6个字符以后的3个字符,即aa2
  echo %p:~0,3%            #显示前3个字符,即aa1
  echo %p:~-2%             #显示最后面的2个字符,即b2
  echo %p:~0,-2%           #显示除了最后2个字符以外的其它字符,即aa1bb1aa2b
  echo %p:aa=c%            #用c替换变量p中所有的aa,即显示c1bb1c2bb2
  echo %p:aa=%             #将变量p中的所有aa字符串置换为空,即显示1bb12bb2
  echo %p:*bb=c%           #第一个bb及其之前的所有字符被替换为c,即显示c1aa2bb2
  set p=%p:*bb=c%          #设置变量p,赋值为 %p:*bb=c% ,即c1aa2bb2
  set /a p=39              #设置p为数值型变量,值为39
  set /a p=39/10           #支持运算符,有小数时用去尾法,39/10=3.9,去尾得3,p=3
  set /a p=p/10            #用 /a 参数时,在 = 后面的变量可以不加%直接引用
  set /a p="1&0″           #"与"运算,要加引号。其它支持的运算符参见set/?
  set p=                   #取消p变量
  set /p p=请输入
  屏幕上显示"请输入",并会将输入的字符串赋值给变量p
  注意这条可以用来取代 choice 命令
  注意变量在 if 和 for 的复合语句里是一次性全部替换的,如
  @echo off
  set p=aaa
  if %p%==aaa (
  echo %p%
  set p=bbb
  echo %p%
  )
  结果将显示
  aaa
  aaa
  因为在读取 if 语句时已经将所有 %p% 替换为aaa
  这里的""替换"",在 /? 帮助里就是指""扩充""、""环境变量扩充""
  可以启用"延缓环境变量扩充",用 ! 来引用变量,即 !变量名!
  @echo off
  SETLOCAL ENABLEDELAYEDEXPANSION
  set p=aaa
  if %p%==aaa (
  echo %p%
  set p=bbb
  echo !p!
  )
  ENDLOCAL
  结果将显示
  aaa
  bbb
  还有几个动态变量,运行 set 看不到
  %CD%                    #代表当前目录的字符串
  %DATE%                  #当前日期
  %TIME%                  #当前时间
  %RANDOM%                #随机整数,介于0~32767
  %ERRORLEVEL%            #当前 ERRORLEVEL 值
  %CMDEXTVERSION%         #当前命令处理器扩展名版本号
  %CMDCMDLINE%            #调用命令处理器的原始命令行
  可以用echo命令查看每个变量值,如 echo %time%
  注意 %time% 精确到毫秒,在批处理需要延时处理时可以用到
  32 start
  批处理中调用外部程序的命令,否则等外部程序完成后才继续执行剩下的指令
  33 call
  批处理中调用另外一个批处理的命令,否则剩下的批处理指令将不会被执行
  有时有的应用程序用start调用出错的,也可以call调用
  34 choice (外部命令)
  选择命令
  让用户输入一个字符,从而选择运行不同的命令,返回码errorlevel为1234……
  win98里是choice.com
  win2000pro里没有,可以从win98里拷过来
  win2003里是choice.exe
  choice /N /C y /T 5 /D y>nul
  延时5秒
  35 assoc 和 ftype
  文件关联
  assoc 设置'文件扩展名'关联,关联到'文件类型'
  ftype 设置'文件类型'关联,关联到'执行程序和参数'
  当你双击一个.txt文件时,windows并不是根据.txt直接判断用 notepad.exe 打开
  而是先判断.txt属于 txtfile '文件类型'
  再调用 txtfile 关联的命令行 txtfile=%SystemRoot%"system32"NOTEPAD.EXE %1
  可以在""文件夹选项""→""文件类型""里修改这2种关联
  assoc             #显示所有'文件扩展名'关联
  assoc .txt        #显示.txt代表的'文件类型',结果显示 .txt=txtfile
  assoc .doc        #显示.doc代表的'文件类型',结果显示 .doc=Word.Document.8
  assoc .exe        #显示.exe代表的'文件类型',结果显示 .exe=exefile
  ftype             #显示所有'文件类型'关联
  ftype exefile     #显示exefile类型关联的命令行,结果显示 exefile=""%1"" %*
  assoc .txt=Word.Document.8
  设置.txt为word类型的文档,可以看到.txt文件的图标都变了
  assoc .txt=txtfile
  恢复.txt的正确关联
  ftype exefile=""%1"" %*
  恢复 exefile 的正确关联
  如果该关联已经被破坏,可以运行 command.com ,再输入这条命令
  36 pushd 和 popd
  切换当前目录
  @echo off
  c: & cd" & md mp3         #在 C:" 建立 mp3 文件夹
  md d:"mp4                 #在 D:" 建立 mp4 文件夹
  cd /d d:"mp4              #更改当前目录为 d:"mp4
  pushd c:"mp3              #保存当前目录,并切换当前目录为 c:"mp3
  popd                      #恢复当前目录为刚才保存的 d:"mp4
  37 for
  循环命令
  这个比较复杂,请对照 for/? 来看
  for %%i in (c: d: e: f:) do echo %%i
  依次调用小括号里的每个字符串,执行 do 后面的命令
  注意%%i,在批处理中 for 语句调用参数用2个%
  默认的字符串分隔符是""空格键"",""Tab键"",""回车键""
  for %%i in (*.txt) do find ""abc"" %%i
  对当前目录里所有的txt文件执行 find 命令
  for /r . %%i in (*.txt) do find ""abc"" %%i
  在当前目录和子目录里所有的.txt文件中搜索包含 abc 字符串的行
  for /r . %%i in (.) do echo %%~pni
  显示当前目录名和所有子目录名,包括路径,不包括盘符
  for /r d:"mp3 %%i in (*.mp3) do echo %%i>>d:"mp3.txt
  把 d:"mp3 及其子目录里的mp3文件的文件名都存到 d:"mp3.txt 里去
  for /l %%i in (2,1,8) do echo %%i
  生成2345678的一串数字,2是数字序列的开头,8是结尾,1表示每次加1
  for /f %%i in ('set') do echo %%i
  对 set 命令的输出结果循环调用,每行一个
  for /f ""eol=P"" %%i in ('set') do echo %%i
  取 set 命令的输出结果,忽略以 P 开头的那几行
  for /f %%i in (d:"mp3.txt) do echo %%i
  显示 d:"mp3.txt 里的每个文件名,每行一个,不支持带空格的名称
  for /f ""delims="" %%i in (d:"mp3.txt) do echo %%i
  显示 d:"mp3.txt 里的每个文件名,每行一个,支持带空格的名称
  for /f ""skip=5 tokens=4"" %%a in ('dir') do echo %%a
  对 dir 命令的结果,跳过前面5行,余下的每行取第4列
  每列之间的分隔符为默认的""空格""
  可以注意到 dir 命令输出的前5行是没有文件名的
  for /f ""tokens=1,2,3 delims=- "" %%a in ('date /t') do (
  echo %%a
  echo %%b
  echo %%c
  )
  对 date /t 的输出结果,每行取1、2、3列
  第一列对应指定的 %%a ,后面的 %%b 和 %%c 是派生出来的,对应其它列
  分隔符指定为 - 和""空格"",注意 delims=- 后面有个""空格""
  其中 tokens=1,2,3 若用 tokens=1-3 替换,效果是一样的
  for /f ""tokens=2* delims=- "" %%a in ('date /t') do echo %%b
  取第2列给 %%a ,其后的列都给 %%b
  38 subst (外部命令)
  映射磁盘。
  subst z: "server"d       #这样输入z:就可以访问"server"d了
  subst z: /d               #取消该映射
  subst                     #显示目前所有的映时
  39    xcopy (外部命令)
  文件拷贝
  xcopy d:"mp3 e:"mp3 /s/e/i/y
  复制 d:"mp3 文件夹、所有子文件夹和文件到 e:" ,覆盖已有文件
  加 /i 表示如果 e:" 没有 mp3 文件夹就自动新建一个,否则会有询问
  -------------------------------------------------- --------------------------------------------------- ---------
  PART III MANNUAL IN DOS
  Runs a specified command for each file in a set of files.
  FOR %variable IN (set) DO command [command-parameters]
  %variable  Specifies a single letter replaceable parameter.
  (set)      Specifies a set of one or more files.  Wildcards may be used.
  command    Specifies the command to carry out for each file.
  command-parameters
  Specifies parameters or switches for the specified command.
  To use the FOR command in a batch program, specify %%variable instead
  of %variable.  Variable names are case sensitive, so %i is different
  from %I.
  If Command Extensions are enabled, the following additional
  forms of the FOR command are supported:
  FOR /D %variable IN (set) DO command [command-parameters]
  If set contains wildcards, then specifies to match against directory
  names instead of file names.
  FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
  Walks the directory tree rooted at [drive:]path, executing the FOR
  statement in each directory of the tree.  If no directory
  specification is specified after /R then the current directory is
  assumed.  If set is just a single period (.) character then it
  will just enumerate the directory tree.
  FOR /L %variable IN (start,step,end) DO command [command-parameters]
  The set is a sequence of numbers from start to end, by step amount.
  So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
  generate the sequence (5 4 3 2 1)
  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]
  or, if usebackq option present:
  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]
  filenameset is one or more file names.  Each file is opened, read
  and processed before going on to the next file in filenameset.
  Processing consists of reading in the file, breaking it up into
  individual lines of text and then parsing each line into zero or
  more tokens.  The body of the for loop is then called with the
  variable value(s) set to the found token string(s).  By default, /F
  passes the first blank separated token from each line of each file.
  Blank lines are skipped.  You can override the default parsing
  behavior by specifying the optional "options" parameter.  This
  is a quoted string which contains one or more keywords to specify
  different parsing options.  The keywords are:
  eol=c           - specifies an end of line comment character
  (just one)
  skip=n          - specifies the number of lines to skip at the
  beginning of the file.
  delims=xxx      - specifies a delimiter set.  This replaces the
  default delimiter set of space and tab.
  tokens=x,y,m-n  - specifies which tokens from each line are to
  be passed to the for body for each iteration.
  This will cause additional variable names to
  be allocated.  The m-n form is a range,
  specifying the mth through the nth tokens.  If
  the last character in the tokens= string is an
  asterisk, then an additional variable is
  allocated and receives the remaining text on
  the line after the last token parsed.
  usebackq        - specifies that the new semantics are in force,
  where a back quoted string is executed as a
  command and a single quoted string is a
  literal string command and allows the use of
  double quotes to quote file names in
  filenameset.
  Some examples might help:
  FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
  would parse each line in myfile.txt, ignoring lines that begin with
  a semicolon, passing the 2nd and 3rd token from each line to the for
  body, with tokens delimited by commas and/or spaces.  Notice the for
  body statements reference %i to get the 2nd token, %j to get the
  3rd token, and %k to get all remaining tokens after the 3rd.  For
  file names that contain spaces, you need to quote the filenames with
  double quotes.  In order to use double quotes in this manner, you also
  need to use the usebackq option, otherwise the double quotes will be
  interpreted as defining a literal string to parse.
  %i is explicitly declared in the for statement and the %j and %k
  are implicitly declared via the tokens= option.  You can specify up
  to 26 tokens via the tokens= line, provided it does not cause an
  attempt to declare a variable higher than the letter 'z' or 'Z'.
  Remember, FOR variables are single-letter, case sensitive, global, 
  and you can't have more than 52 total active at any one time.
  You can also use the FOR /F parsing logic on an immediate string, by
  making the filenameset between the parenthesis a quoted string,
  using single quote characters.  It will be treated as a single line
  of input from a file and parsed.
  Finally, you can use the FOR /F command to parse the output of a
  command.  You do this by making the filenameset between the
  parenthesis a back quoted string.  It will be treated as a command
  line, which is passed to a child CMD.EXE and the output is captured
  into memory and parsed as if it was a file.  So the following
  example:
  FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
  would enumerate the environment variable names in the current
  environment.
  In addition, substitution of FOR variable references has been enhanced.
  You can now use the following optional syntax:
  %~I         - expands %I removing any surrounding quotes (")
  %~fI        - expands %I to a fully qualified path name
  %~dI        - expands %I to a drive letter only
  %~pI        - expands %I to a path only
  %~nI        - expands %I to a file name only
  %~xI        - expands %I to a file extension only
  %~sI        - expanded path contains short names only
  %~aI        - expands %I to file attributes of file
  %~tI        - expands %I to date/time of file
  %~zI        - expands %I to size of file
  %~$PATH:I   - searches the directories listed in the PATH
  environment variable and expands %I to the
  fully qualified name of the first one found.
  If the environment variable name is not
  defined or the file is not found by the
  search, then this modifier expands to the
  empty string
  The modifiers can be combined to get compound results:
  %~dpI       - expands %I to a drive letter and path only
  %~nxI       - expands %I to a file name and extension only
  %~fsI       - expands %I to a full path name with short names only
  %~dp$PATH:I - searches the directories listed in the PATH
  environment variable for %I and expands to the
  drive letter and path of the first one found.
  %~ftzaI     - expands %I to a DIR like output line
  In the above examples %I and PATH can be replaced by other valid
  values.  The %~ syntax is terminated by a valid FOR variable name.
  Picking upper case variable names like %I makes it more readable and
  avoids confusion with the modifiers, which are not case sensitive.
  References: 
  [1] http://www.allenware.com/
  [2] http://www.chebucto.ns.ca/~ak621/DOS/BatExamp.html #Batch
  [3] http://www.cublog.cn/u/31179/showart_1387404.html
  [4] DOS CMD Help Mannual

猜你喜欢

转载自bzu334fc.iteye.com/blog/1361615