Aug 17, 2008

Batch Programming Tricks --- 4

Limit DIR output to only the file or directory you specify.
In cases where you are looking for an extensionless file or directory, only the name you specify will be in the DIR output, even though there may exist one or more files with the same basename and an extension. It can be used on all files because a dot following a file with an extension is ignored.
DIR/A-D/-P FileName.
DIR/AD/-P DirName.

Delete a file with copy
COPY nul filename

Xcopy one file to another without being asked if it's a file or directory.
ECHO F |XCOPY.EXE file1 file2

Xcopy a file to another directory w/o pipe.
XCOPY c:\example1.fil w:\temp\

Xcopy a file to another directory w/o pipe.
XCOPY c:\example1.fil w:\temp\*example1.fil

Use mode.com to truncate a string.
:: truncate one character, or up to and including a delimiter.
MODE name.ext
:: returns: Invalid parameter - name
MODE think/
:: returns: Invalid parameter - thin

Determine if a file is a 0 byte file without deleting it.
:: is0byte.bat
@ECHO off
COPY>nul %1 nul |FIND "1 file(s) copied"
IF not errorlevel=1 ECHO %1 is not a 0 byte file
IF errorlevel=1 ECHO %1 is a 0 byte file

:: is0byte2.bat
COPY %1 nul |FIND " 0 file" >nul
IF not errorlevel=1 ECHO %1 is a 0 byte file
IF errorlevel=1 ECHO %1 is not a 0 byte file

Place a line without a CR/LF (Carriage Return/Line Feed) into a file.
After creating this input file which has an End Of File character as its last character, you can TYPE the input file into a new batch file which will not have a CR/LF. See FAQ 57.
:: setvar.inp
@ECHO off
:: EOF character created in edit by Ctrl+P+Z
SET %1=EOF

Get input from file into variable.
Where result1.dat contains command output or other text. This example places the current directory into a variable.
:: result.bat
@ECHO off
CD > result1.dat ECHO. >> result1.dat
DATE <> result1.bat
ECHO set curdir=%%4> enter.bat
FOR %%C IN (CALL DEL) DO %%C result1.bat
DEL enter.bat
:: %optional% DEL result1.dat
:: %optional% ECHO. current directory is %curdir%

Timestamp and/or datestamp (touch) a file with the current system date and time.
COPY/Y filename /B+,,

No comments: