Batchography: 8 Batch File Tricks for Daily Use

Introduction

Back in 2016, I decided to learn as much as I can about the Batch files programming language because Batch was my first programming language when I was a kid. Today I share with you some of those Batchography tips.

Background

If you have done some basic command prompt work (cmd.exe) and/or have written basic Batch files, then please skip this section.

If you have never done Batch files programming, then welcome. Just run "cmd.exe" to open the command prompt, then type: "notepad hello.bat".

In Notepad, just type the following:

@echo off
echo Welcome to the Batch Programming World!

Close Notepad and save the file. Now back to the command prompt, type: "hello.bat" and hit the ENTER key.

That's it! That was your first Batch file script which outputs the message from above.

It is advisable that you know some programming concepts to proceed with the remainder of this article.

Trick #1 - Taking user input and doing arithmetic operations

Often times, it is very important to write interactive scripts that take input from the user and carry arithmetic operations if needed.

To read user input, we can use the following syntax:

SET /P VarName=The prompt text

So for example, to ask the user for his/her name and display it back again, we can do the following:

It is important not to pollute the environment variables namespace when using the "SET" command and therefore it is a good practice to start your script with the "setlocal" command that will revert the environment variable changes when the script terminates.

Similarily, to do arithmetic operations, we can use the following syntax:

SET /A Number=Expression

For example:

SET /A Number=1+2+3+4

Would compute into the variable "Number" the value "10".

Now, we can combine those two tricks to create a small integer expression calculator:

@echo off
setlocal
:repeat
SET /P Expr="Please enter an expression (or 'q') to quit:"
SET /A Result=%Expr%
if "%Expr%"=="" goto :eof
if "%Expr%"=="q" goto :eof
echo The result is %Result%
goto repeat

Here's a sample output from this script:

C:\Temp\Batchography>expr-calc.bat
Please enter an expression (or 'q') to quit:1+2+3
The result is 6
Please enter an expression (or 'q') to quit:-5+2
The result is -3
Please enter an expression (or 'q') to quit:q
C:\Temp\Batchography>

Trick #2 - Number counting

Number counting can come in handy in many scenarios. It could be used to create numbered dummy folders, write an algorithm that requires counting, or anything else you can think of.

In Batch files, to count, you can use the following syntax:

FOR /L %variable IN (start, step, end) DO command [command-parameters]

Let's illustrate by writing a small script that creates 10 dummy folders: "folder1" to "folder10":

So let's assume we have the following files:

@echo off
for /L %%a in (1, 1, 10) do (
mkdir folder%%a
)

For example, let us write the sigma function (do the addition from 1 to N):

@echo off
setlocal
:repeat
SET /P N="Please N for the sigma computation:"
SET /A Result=0
for /L %%i in (1, 1, %N%) do (
SET /A Result=Result+%%i
)
echo Sigma(%N%)=%Result%

Trick #3 - Reading a text file line by line in Batch files

Reading from a text file, one line at a time can be very handy for text scanning and transformation. Use the "FOR /F" syntax like this:

@echo off
for /f "delims=" %%a in (the-file.txt) DO (
ECHO Line is: %%a
)

We can implement a very basic non-empty lines counter in text files using the Batch language like this:

Trick #4 - String substitution

With the Batch scripting language, it is possible to do string substitution. To achieve that, we have to have the string in question inside an environment variable. We can then use the following syntax:

%VarName:StringToBeMatched=StringToBeReplacedWith%

Let's write an interactive script that replaces the word "books" with "ebooks" in the file "email.txt":

Reading books was the norm during his grandfather's time.
People used to carry books with them to school in order to read and study.
Some say that books will become obsolete one day. Who knows.

The following script will do the string substitution and generate a new file called "new-email.txt":

There's a slight drawback in this polyglot script. The first line ("/*" a C multi-line comment opening) is not a valid command and it will cause an error but we redirect the error to the nul device. We close the multi-line comment (with "*/") shortly after exiting the Batch file.

Trick #7 - Tokenizing commands output

It is possible to execute a command then break its output into tokens. To achieve this, we will use the "FOR /F" syntax.

From the command prompt, to query the registry and retrieve the language ID, we can use the "reg.exe" command like such:

We have two lines output. We only care about the second line and the 3rd token (if we tokenize the string using the space character). To retrieve the 0409 value and write a Batch script to detect the system language, we can do the following:

The function "add", is just a label and what comes after it in the same line are ignored / free text. As a convention, we put the argument number and its description. The "add" function is defined to take a return variable name (argument #1) and two numbers "a" (argument #2) and "b" (argument #3).

The "main" function calls "add" using the "call :func_name" syntax and passing the arguments thereafter. When "add" returns, it may call "goto :eof" or "exit /b <return_code>".

Conclusion

The Batch programming is an old but a beautiful language. It has so many features that I was delighted to research and learn about.