Aug 17, 2008

Batch Programming Tricks --- 1

Alternative ways to get directory listing.
DIR DIR * DIR . DIR. DIR : DIR: DIR , DIR,
The last two also list system and hidden files.

One or more . (dots) can represent a directory.
Sometimes it's easier to use dots to represent directories. For example, if you'd like to move a file from another directory to the current, instead of writing the path to the current directory (which move.exe requires), use a dot: MOVE.EXE Path\anyfile .

This can be demonstrated with the DIR command.
One dot represents the current directory: DIR .
Two dots represent the parent directory: DIR ..
Three dots represent the directory above that: DIR ...
And so on.

Directory listing of extentionless files.
DIR/A *. will list all files without extensions.

Add or remove file extensions (except system or hidden files).
REN *. *.txt will add .txt extension to files without extensions.
REN *.txt *. will remove .txt extension on files that have it.

Rename multiple files (except system or hidden files).
REN *.bat *.txt will rename all .bat files to .txt files.
REN *.txt 1*.txt will rename all .txt files so their first character is 1.

Use %temp%.\ (case is irrelevant) to represent the temp variable.
The temp variable can be set with or without a backslash, ie. c:\temp or c:\temp\, which can be problematic when using the variable in a batch file. Using temp%.\ will refer correctly to the temp directory whether it has been set with a backslash or not. This method can be used with any variable whose value is set to a directory (provided the directory name has no extension!).

Use ..\ as the last directory in your Path statement.
No matter where you are, the parent directory will always be in the Path.

Change Drive and Directory easily.
There can be many reasons for changing drive and directory in a batch file, and this can be difficult if we only have a path and directory to go on. This can be accomplished with startling ease when one knows the secret, however. A drive can be made current just by entering a full path and directory at the prompt, provided a backslash is added at the end, ie. D:\AnyDir\, which entered at the prompt will make the D: drive current, if it is a valid drive. Oddly enough, the directory can be bogus and this will work nonetheless. If our directory is indeed valid, we can after changing drives, change to the directory by adding CD in front and repeating it without the backslash so we have, D:\AnyDir\ followed by CD D:\AnyDir Here's how it looks in a batch file:

@ECHO off
:: cdd.bat (Change Drive and Directory)
:: Where %1 is a full path and directory without backslash.
:: Example usage: CDD D:\ValidDir or CDD D: (for root)
%1\
CD %1

Suppress a command's output.
Works with most commands.
COPY file1 file2 >nul

Suppress a batch file's output.
COMMAND/CTEST.BAT >nul

No comments: