- Why Batch Files?
- Creating and Using Batch Files
- Batch File Programming
- Displaying Information in Batch Files
- Argument Substitution
- Argument Editing
- Conditional Processing with If
- Processing Multiple Arguments
- Working with Environment Variables
- Processing Multiple Items with the For Command
- Using Batch File Subroutines
- Prompting for Input
- Useful Batch File Techniques
Argument Editing
CMD lets you modify arguments as they're replaced on the command line. Most of the modifications assume that the argument is a filename and let you extract or fill in various parts of the name. When command extensions are enabled, CMD can insert edited versions of the arguments by placing a tilde (~) and some additional characters after the % sign. The editing functions let you manipulate filenames passed as arguments. Table 12.2 lists the edit options, using argument number 1 as an example.
Table 12.2. Argument Editing Expressions
Expression |
Result |
%~1 |
Removes surrounding quotes ("). |
%~f1 |
Fully qualified pathname. |
%~d1 |
Drive letter only. |
%~p1 |
Path only. |
%~n1 |
Filename only. |
%~x1 |
File extension only. |
%~s1 |
Short DOS 8.3 file and path. |
%~a1 |
File attributes. |
%~t1 |
Modification date/time of file. |
%~z1 |
Length of file in bytes. |
%~$PATH:1 |
Fully qualified name of the first matching file when searching PATH. If no file is found, the result is a zero-length string. The filename must include the proper extension; PATHEXT is not used. |
For example, if I ran a batch file with the argument "under the hood.doc", the results would be as follows:
Expression |
Result |
%~1 |
under the hood.doc |
%~f1 |
C:\book\ch11\under the hood.doc |
%~d1 |
C: |
%~p1 |
\book\ch11 |
%~n1 |
under the hood |
%~x1 |
.doc |
%~s1 |
C:\book\ch11\UNDERT~1.DOC |
%~a1 |
--a------ |
%~t1 |
04/20/2002 12:42 PM |
%~z1 |
45323 |
%~$PATH:1 |
Here's how these features might be used: Suppose I have a series of files that I need to sort. The input files could come from any folder, but I want to store the sorted files in C:\sorted and give them the extension .TAB regardless of what the original extension was. I can write a batch file named sortput.bat to do this:
@echo off sort <%1 >c:\sorted\%~n1.tab
The sort command will read the file as I've specified it on the command line, but the output file will use only the base part of the input file's name. If I run the command
sortput "c:\work files\input.txt"
the substituted command will be
sort <"c:\work files\input.txt" >c:\sorted\input.tab