Windows 7 / Getting Started

Using the for Command's Variable

As the for command runs through each of the files or words named in the set list, the variable you specify on the command line takes each of the set's values in turn. If the variable is specified as, say, %x, wherever %x appears after the keyword do, it is be replaced by the variable's value. CMD has added some additional ways to extract information from the variable, most of which treat the variable as a filename and let you extract just specific filename components.This makes it possible to construct for loops that could, for example, run through all the .DOC files in a folder and copy them to files named .BACKUP.

CMD edits the value of the variable based on extra characters you place after the % symbol and substitutes the edited version into the command line. The variable edits that CMD offers are listed in Table below (The same edits are available for the command line and subroutine arguments in batch files.)

Variable-Editing Functions
Expression	Result
%n 		Argument or variable n without editing.
%~n 		Removes surrounding quotes (" ").
%~fn 		Fully qualified pathname.
%~dn 		Drive letter only.
%~pn 		Path only.
%~nn 		Filename only.
%~xn 		File extension only.
%~sn 		Short DOS 8.3 file and path.
%~an 		File attributes.
%~tn 		Modification date/time of file.
%~zn 		Length of file in bytes.
%~$PATH:n 	Fully qualified name of first matching file when
                PATH is searched. If no file is found, the result
                is a zero-length string.The filename must include
                the proper extension; PATHEXT is not used.

The filename modifiers can be used in combination (for example, %~dpn returns the combined drive and path).

Tip When using variable edits, it's best to use uppercase letters for your variable so that CMD can distinguish between the editing characters, which must always be in lowercase, and your variable. (You might notice that $PATH: is not in lowercase-the dollar sign and colon make it clear to CMD that this is an editing function and not the variable P.)

As an example, the following for loop copies only files under 1MB in size to a network folder:

for %X in (*.*) do if %~zX LSS 1000000 copy %X \\bali\myfiles
[Previous] [Contents] [Next]