String Operations
When writing batch files, you often need to process strings, for example to clean up file names or format log output.
Batch files have no dedicated string functions, but the special syntax of variable expansion lets you perform replacement, substring extraction, and concatenation.
Replacing Strings
To replace part of a string stored in a variable, use the following syntax.
set newvar=%variable:old=new%
Example
@echo off
setlocal
set TEXT=Hello World
echo Original: %TEXT%
set TEXT=%TEXT:World=Japan%
echo Replaced: %TEXT%
endlocal
Converting Path Separators
set PATH_STR=C:\Users\user\Documents
set PATH_STR=%PATH_STR:\=/%
echo %PATH_STR%

中小企業経営者のためのRPA入門 RPA導入を成功させる方法

60分でわかる! AIエージェント 超 入門

コマンドラインの黒い画面が怖いんです。

知識・才能ゼロでもらく~に月10万円稼ぐ! よくわかるAI副業超入門
Deleting Characters (Replacing with an Empty String)
set TEXT= Hello
set TEXT=%TEXT: =%
echo [%TEXT%]
String replacement ignores case. %TEXT:hello=Hi% replaces Hello, HELLO, and hello alike.
Use * to delete everything up to and including a given string.
set TEXT=key=value
set VALUE=%TEXT:*==%
echo %VALUE%
The string to be replaced cannot begin with =. Strings containing % or ! may also not be handled correctly by ordinary replacement.
Extracting Substrings
To extract part of a variable, use the following syntax.
%variable:~start,length%
| Parameter | Description |
|---|---|
| start | Zero-based index |
| length | Number of characters to extract (to the end if omitted) |
| Negative value | Counts from the end of the string |
Example
@echo off
setlocal
set TEXT=ABCDEFGHIJ
rem First 3 characters
echo %TEXT:~0,3%
rem 3 characters starting at the 4th (index 3 because it is zero-based)
echo %TEXT:~3,3%
rem Skip the first 2 characters
echo %TEXT:~2%
rem Last 3 characters
echo %TEXT:~-3%
rem Everything except the last 3 characters
echo %TEXT:~0,-3%
endlocal
Zero Padding
This example pads numbers to three digits.
@echo off
setlocal enabledelayedexpansion
for /L %%i in (1,1,5) do (
set NUM=00%%i
set NUM=!NUM:~-3!
echo !NUM!
)
endlocal
Zero padding is used frequently for sequential file names and log formatting. Prefix the number with zeros using set NUM=00%%i, then take the last three characters with !NUM:~-3!.
Concatenating Strings
In batch files, you can concatenate strings simply by writing variables next to each other.
@echo off
setlocal
set FIRST=Hello
set SECOND=World
set RESULT=%FIRST% %SECOND%
echo %RESULT%
endlocal
Building a String in a Loop
@echo off
setlocal enabledelayedexpansion
set RESULT=
for %%f in (*.txt) do (
set RESULT=!RESULT! %%f
)
echo Files found:%RESULT%
endlocal
Getting the Length of a String
Batch files have no built-in way to get the length of a string. Instead, you can extract one character at a time and count until the result is empty.
@echo off
setlocal enabledelayedexpansion
set TEXT=Hello World
set LEN=0
:LOOP
if not "!TEXT:~%LEN%,1!"=="" (
set /a LEN+=1
goto LOOP
)
echo String: %TEXT%
echo Length: %LEN%
endlocal
You cannot write %TEXT:~%LEN%,1% when the start position or length is a variable. As in the example above, enable enabledelayedexpansion and write !TEXT:~%LEN%,1!. See the delayed expansion guide for details.
Things to Keep in Mind
- Assign values with
set "VAR=value". Inset TEXT=abca trailing space becomes part of the value. Wrapping the assignment in quotes, as inset "TEXT=abc", excludes any spaces outside the quotes. - A start position beyond the string length returns an empty result. When counting from the end, as in
%TEXT:~-3%, a string shorter than 3 characters is returned in full. - There is no case-conversion feature. If you need one, consider combining
forwith replacement, or use PowerShell. - Replacement and substring extraction give unexpected results on undefined variables. Check first with
if defined VARNAME.
Working with File Paths
In batch files, the for variable modifiers let you extract each part of a file path.
@echo off
set FILE=C:\Users\user\Documents\report.txt
for %%F in ("%FILE%") do (
echo Full path: %%~fF
echo Drive: %%~dF
echo Folder: %%~pF
echo File name: %%~nF
echo Extension: %%~xF
echo Name + ext: %%~nxF
)
| Modifier | Description |
|---|---|
~f | Full path |
~d | Drive letter |
~p | Path (folder part) |
~n | File name without extension |
~x | Extension |
~nx | File name with extension |
Summary
| Operation | Syntax |
|---|---|
| Replace a string | %variable:old=new% |
| Extract a substring | %variable:~start,length% |
| Extract from the end | %variable:~-length% |
| Concatenate strings | set RESULT=%A%%B% |
| Delete everything before a string | %variable:*string=% |