Thursday, November 6, 2025

String Manipulation in Batch Scripting

Look at the following batch script in Example1 to understand the String Manipulation in Batch Scripting. The set statement is used to declare and initialize the variable named filename. In each ECHO statement, the variable filename is manipulated. The colon symbol implies that the command line interpreter expands the variable till it reaches the colon. Now at compile time, string is expanded and it becomes document.pdf. Now the string manipulation operation begins after tilde(~) symbol. This tilde sign implies that it will start working on the string "document.pdf". The minus(-) sign is followed by a number e.g. 1,2,3,4 etc. This implies that 1,2,3,4 number of characters will be removed from the end of the string and returned. Look at the output for better comprehension.

EXAMPLE1. Remove Characters from the End of string


@echo off
set "filename=document.pdf"
echo "%filename:~-1%" :: Last 1 character
echo "%filename:~-2%" :: Last 2 character
echo "%filename:~-3%" :: Last 3 character
echo "%filename:~-4%" :: Last 4 character
echo "%filename:~-6%"
pause

OUTPUT

"f" :: Last 1 character
"df" :: Last 2 character
"pdf" :: Last 3 character
".pdf" :: Last 4 character
"nt.pdf"
Press any key to continue . . .

EXAMPLE2. Remove Characters from the Start of string

In example1, we saw how to remove characters from the end of string. Now we see how to remove characters from the start position of string. Already we have seen that string manipulation begins with ~ sign. If tilde is followed by a number such as 1 or 2 etc then that number of characters from removed from the starting posiotn of string. Look at the output for better comprehension.

@echo off
set "filename=document.pdf"
echo "%filename:~1%" :: First 1 character
echo "%filename:~2%" :: First 2 characters
echo "%filename:~3%" :: First 3 characters
echo "%filename:~4%" :: First 4 characters
@pause

OUTPUT

"ocument.pdf" :: First 1 character
"cument.pdf" :: First 2 characters
"ument.pdf" :: First 3 characters
"ment.pdf" :: First 4 characters
Press any key to continue . . .

EXAMPLE3. Add Characters in the beginning of string

Prefixing Text to string in batch scripting is very easy. You need no special operator for this. Look at the following example to prefix each subfolder in a folder:

Prefix Folders in a Directory or Drive

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

REM Create 5 folders
SET "folder_name=Folder"
SET "count=5"
FOR /L %%c in (1,1,5) DO (
    MKDIR "%folder_name%_%%c"
)

REM Prefix Each Folder Name
SET "folder_prefix=Batch_Program_"
FOR /D %%x in ("%folder_name%*") DO (
    SET "original=%%x"
    REM The REN command is to change the folders name.
    REM We use !original! here to get the value set in the same block.
    REN "!original!" "%folder_prefix%!!original!"
    ECHO Renamed: "!original!" to "%folder_prefix%!!original!"
)

ENDLOCAL
pause

REMARK: You must have clarity about string expansion at compile time and at run time. The string variable sandwiched between % e.g. %text_string_variable% is expanded at compile time but !text_string_variable! is expanded at runtime. Since variable original is declared at runtime when the FOR loop is executing, so the expansion of original variable need runtime variable expandor i.e. exclamation sign. The value of variable original is decided by %%x which value is decided at runtime.


EXAMPLE4. Get Substring of a String

Look at the following example to see how substring from a string is derived. The full explanation of string manipulation is given ahead together with another example.

@echo off
REM Set blue background and light yellow foreground color
color 1E
:: The variable must be immediately followed by = sign to initialize
set myname=AjeetKumar2023

:: returns AjeetKumar2023
echo %myname%

:: returns Ajeet The start offset is 0 and length offset is 5
:: length offset tells how many characters to grab
echo %myname:~0,5%

:: returns Kumar2023, skip first 5 chars and peek next all chars
:: start offset is 5 and length offset is not given
:: So, it will grab all characters from start offset position
echo %myname:~5%

:: returns mar20, skip first 7 characters and grab next 5 characters 
echo %myname:~7,5%

:: returns ma, skip first 7 characters and grab next 2 chars
echo %myname:~7,2%

:: returns Kumar
:: It skips first 5 characters and 
:: length offset from end is 4. What does it mean?
:: It means that grabbing direction will still be from start position
:: but length offset tells the position where the grabbing will stop.
echo %myname:~5,-4%

pause
@echo on

EXAMPLE5. Get String from in Between of a string

Now we see how to remove first 3 characters from the start and 4 characters from the end and then return the remaining string?

The core command to achieve this uses the syntax:

%variable:~start,length%

The tilde symbol tells about string manipulation operation.
The start is a number which can be positive or negative. Already we have seen 2 examples in this regard. We have not seen the second parameter which is length.
The basic idea is to manipulate a string variable, we use colon(:) after the variable to denote that the variable expansion is done now. The tilde denotes to start string variable manipulation. If start is postive number then skip that number of characters of the string variable from the beginning. Similarly, if start is negative number then skip that number of characters of the string variable from the end. This much we have already seen.

Now, we look at length parameter. The length can be positive or negative as well.

Step 1: Removing the First 3 Characters (from the Start)
To remove the first 3 characters, you start counting the position from the 4th character (which is index 3 in programming terms, but the offset is simply 3 in batch).

Syntax: !OriginalString:~3!

This takes the string starting at the 3rd character offset (i.e., the 4th character) and goes to the end.

Step 2: Removing the Last 4 Characters (from the End)
Next, to remove the last 4 characters from the result of Step 1, you use a negative number for the length parameter.

Syntax: !StringFromStep1:~0,-4!

~0 means start at the beginning of StringFromStep1.

,-4 means stop 4 characters before the end of StringFromStep1.

Complete Example
Now we look at the complete, working Batch script example. We need to enable Delayed Expansion (setlocal enabledelayedexpansion) to handle the intermediate variable assignment correctly within a block of code.

@echo off
setlocal enabledelayedexpansion

:: 1. Define the original string
set "OriginalString=ABCDEFGHIJKLMNO"
:: Length of OriginalString is 15
:: Characters to keep: D-E-F-G-H-I-J-K
:: Expected Result: DEFGH IJK

echo Original String: **%OriginalString%**
echo.

:: 2. Remove the first 3 characters (A, B, C)
set "TempString=!OriginalString:~3!"
echo After removing first 3 chars (ABC): !TempString!
:: TempString is now: DEFGHIJKLMNO

:: 3. Remove the last 4 characters (L, M, N, O) from the TempString
set "FinalString=!TempString:~0,-4!"
echo After removing last 4 chars (LMNO): **!FinalString!**
echo.

endlocal
pause

OUTPUT
Original String: ABCDEFGHIJKLMNO

After removing first 3 chars (ABC): DEFGHIJKLMNO
After removing last 4 chars (LMNO): DEFGH IJK
This method is the most efficient and standard way to perform this kind of string slicing in Batch scripting.

The SET statement in Batch Script and Loop Variable

Some Facts:

  • The set statement is used to declare and initialize a variable.
  • The variable initialization inside quote is considered best practice.
  • The replaceable parameter is prefixed with % on command line window or %% in batch file. 
  • Note that % is not both side of replaceable parameter as we do with variables declared with set statement.
  • The replaceable parameters are part of loop implicit varibles.
  • The SET statement is used to declare and initialize variable explicitly.
  • The loop variable is implicitly declared.
  • The SET variable can be of more than one letter but loop variable must be of single letter.

@echo off

set x=1222
set "y=234"
set "z=ajeet"
set "myVariable=Ram Krishna"

echo %x% %y% %z% %myVariable%

REM FOR /L implies for loop for a set of numbers
REM (1,3,44) implies (start,step,end) i.e. number between 1 and 44 and step value is 3
FOR /l %%n in (1,3,44) DO (echo %%n)

pause

Hot Topics