How to Get the First N Characters of a String in Batch Script
Extracting the beginning of a string is a very common parsing task. You might need to get a prefix from a long identifier, check the first few characters of a line to determine its type, or create a short unique ID from a longer string like a timestamp. Batch scripting provides a simple, fast, and built-in syntax for this operation using variable expansion, allowing you to get the first N characters of any string with ease.
This guide will teach you the standard syntax for extracting a prefix from a string, how to store it for later use, and the critical rules you need to know, such as the zero-based indexing system and how to use this technique inside a loop.
The Core Syntax: %VariableName:~0,N%
The ability to extract a substring is built directly into the variable expansion mechanism in cmd.exe.
The specific syntax for getting the first N characters is:
%VariableName:~0,N%
VariableName: The name of the variable holding your source string.~: The special character that signals a modifier operation.0: The starting position. To get the beginning of the string, you always start at index 0.,N: The number of characters (the length) you want to extract.
Basic Example: Getting the First 5 Characters
Let's take a sample string and extract the first 5 characters from it.
@ECHO OFF
SET "MyString=ABCDEFGHIJKLMNOP"
ECHO The original string is: %MyString%
REM Get the first 5 characters by starting at 0 and taking a length of 5.
ECHO The first 5 characters are: %MyString:~0,5%
Output:
The original string is: ABCDEFGHIJKLMNOP
The first 5 characters are: ABCDE
Storing the Result in a New Variable
In most scripts, you will want to capture the extracted prefix into a new variable to use it in your logic. This is done with a standard SET command.
@ECHO OFF
SET "TransactionID=TRN-20231027-a94fe5"
REM Extract the 3-character prefix.
SET "TransactionType=%TransactionID:~0,3%"
ECHO The full ID is: %TransactionID%
ECHO The transaction type is: %TransactionType%
IF "%TransactionType%"=="TRN" (
ECHO This is a standard transaction.
)
Output:
The full ID is: TRN-20231027-a94fe5
The transaction type is: TRN
This is a standard transaction.
Common Pitfalls and How to Solve Them
The "Zero-Based" Indexing System
The most common point of confusion for newcomers is that string positions in batch scripting are zero-based. This means the very first character of the string is at position 0, the second is at position 1, and so on.
For the string ABCDE:
- Index
0=A - Index
1=B - Index
2=C
Solution: Always remember this rule. To get a prefix of N characters, the syntax is always %VAR:~0,N%.
Using Substrings Inside a Loop (Delayed Expansion)
If you are modifying a string inside a FOR loop and also trying to take a substring of it in the same loop, you must use delayed expansion. Standard percent variables (%Var%) are expanded only once, before the loop begins executing.
This script repeatedly adds a character to a string and then extracts the first 3 characters of the updated string on each iteration.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSON
SET "MyVar="
FOR %%C IN (A B C D E) DO (
REM Add the next character to the string
SET "MyVar=!MyVar!%%C"
REM Get the first 3 chars of the CURRENT string using delayed expansion
ECHO Full string is: !MyVar!
ECHO First 3 chars are: !MyVar:~0,3!
ECHO.
)
Output:
Full string is: A
First 3 chars are: A
Full string is: AB
First 3 chars are: AB
Full string is: ABC
First 3 chars are: ABC
Full string is: ABCD
First 3 chars are: ABC
Full string is: ABCDE
First 3 chars are: ABC
Practical Example: Creating a Short ID from a Timestamp
This script generates a long, sanitized timestamp and then extracts the first 12 characters to create a shorter, "unique enough" ID for a log file prefix.
@ECHO OFF
SETLOCAL
REM Create a detailed timestamp like 2023102710301550
SET "TIMESTAMP=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%%TIME::=%%TIME:.=%"
SET "TIMESTAMP=%TIMESTAMP: =0%"
ECHO Full timestamp: %TIMESTAMP%
REM Extract the first 12 characters (YYYYMMDDHHMM) for a shorter ID
SET "ShortID=%TIMESTAMP:~0,12%"
ECHO Short ID: %ShortID%
SET "LOG_FILE=AppLog_%ShortID%.log"
ECHO.
ECHO Creating log file: %LOG_FILE%
ECHO Log started > %LOG_FILE%
ENDLOCAL
Conclusion
The substring expansion syntax in batch scripting provides a fast, native, and highly efficient way to get the first N characters of any string.
The key syntax to remember is %VAR:~0,N%.
For reliable scripting, always keep in mind:
- The starting position for a prefix is always
0. - When working with a variable that is changing inside a
FORloop, you must use delayed expansion with exclamation marks:!VAR:~0,N!.
This simple and powerful tool is essential for any script that needs to parse or manipulate string data.