Personal tools

Batch

From MohidWiki

Revision as of 18:51, 11 November 2008 by 192.168.20.177 (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Batch files are the original ms-dos scripting language. A batch file is a script that contains a list of ms-dos commands, with one command per line. When you try to execute the batch file, it will execute the ms-dos commands, one after another, waiting for each command to finish before starting the next one.

Examples

For

The following example will output each line of the text file to the stdout:

> FOR /F %i in (list.txt) DO @echo %~ni

The following example will allow to parse and edit the environment variables:

> for /F %i in ('dir /B /S *_1.dat') do @set fil=%i & copy /Y !fil! !fil:1=2!

If you want to write FOR loops in a batch file instead of the command line, then use %%i instead of %i.

To place the first line of a file into a variable:

> SET /P _MyVar=<MyFilename.txt

To place the last line of a file into a variable:

> FOR /F "tokens=*" %A IN (C:\boot.ini) DO SET TestVar=%A

Nested FOR Loops

> FOR /F %a IN (filelist.txt) DO (FOR /F %b IN (salinitytemperature.txt) DO echo %a %b)

Nested FOR loops encapsulated in a batch file

for /F %%a in (%1) do (
    for /R %%b in (../*) do (
        echo %%a
        echo %%b
    )
)

Misc

Escaping characters

<,|,> and % characters are special characters in dos. To escape them use the ^ character or a double %

> echo ^<example^>
<example>

Displaying blank lines

Use command echo to display a blank line instead of its default status result

>echo.

Sample applications

Here's a combination with a batch file, that creates a clean copy of a MOHID simulation:

> copysimulation MySimulation
#copysimulation.bat content
#Input argument %1 stands for simulation name
@echo off
set COPYHOME=C:\Program Files\2gif
xcopy %1\*.* %1_copy /E /EXCLUDE:%COPYHOME%\exclui.txt
perl %COPYHOME%/replace.pl 's/%2/\.\.\/\.\./g' *
perl %COPYHOME%/replace.pl 's/\\/\//g' *
@echo on

External References