Some basic commands of Windows Batch Scripting


Parsing file using For Loop

Suppose a file mytext.txt contains
firstT 2ndT 3rdT 4thT
;1st2T 2nd2T 3rd2T 4th2T
1st3T 2nd3T 3rd3T

If I want to parse the content of the file I will need to write to the below command
for /F "eol=; tokens=1,2,3* delims= " %i in (myfile.txt) do @echo %i %j %k %l
It means This command parses each line in myfile.txt, ignoring lines that begin with a semicolon and passing the first, second and third token from each line to the FOR body (tokens are delimited by spaces). The body of the FOR statement references %i to get the first token, %j to get the second token, %k to get the third one and %l to get all of the remaining tokens. Delimeter can be any thing and needs to be written after delims=.



Often you could see set /A command in any batch script. The interpretation is like


Set
Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings.
Syntax
set [[/a [expression]] [/p [variable=]] string]
Parameters
/a : Sets string to a numerical expression that is evaluated.
/p : Sets the value of variable to a line of input.
variable : Specifies the variable you want to set or modify.
string : Specifies the string you want to associate with the specified variable.
/? : Displays help at the command prompt.

c:\temp>set dd=20
c:\temp>echo %dd%
20
c:\temp>set /A dd=1%dd% - 80
40
A sample example of Leap Year check

Logic is just for recall :). Here we will be introduced with if else conditional clause also.
c:\temp>set yyyy=2012

c:\temp>set /A tt=%yyyy% % 4
0
c:\temp>set /A tt=%yyyy% % 100
12
c:\temp>set /A tt=%yyyy% % 400
12


The batch file name suppose chkLeapYear.bat and contains below set of codes

@echo off

set yyyy=%1

:LEAPCHK

set /A tt=%yyyy% %% 4

if not %tt%==0 goto SET28

set /A tt=%yyyy% %% 100

if not %tt%==0 goto SET29

set /A tt=%yyyy% %% 400

if %tt%==0 goto SET29

:SET28

echo "%yyyy% Not a Leap Year"

goto Done

:SET29

echo "%yyyy% Is a Leap Year"

:Done


Now run this in cmd prompt
c:\temp>chkLeapYear.bat 1999
"1999 Not a Leap Year"

c:\temp>chkLeapYear.bat 2012
"2012 Is a Leap Year"

Comments

Popular posts from this blog

Restoring Master, Model and MSDB from Netbackup

Oracle Job Operations