String Manipulation
CMD has no string functions like length() or upper(). Instead, the variable expansion syntax itself can cut out part of a value and replace text inside it. These two features, plus a few loops, cover most string work in batch files.
| Syntax | Result |
|---|---|
%var:~start% |
from position start to the end |
%var:~start,len% |
len characters starting at start |
%var:~-n% |
the last n characters |
%var:~start,-n% |
from start, dropping the last n characters |
%var:old=new% |
every old replaced by new (case-insensitive) |
%var:old=% |
every old removed |
%var:*old=new% |
everything up to and including the first old replaced |
Positions start at 0.
Substrings: %var:~start,length%
@echo off
set "word=Microsoft"
echo first 5: %word:~0,5%
echo from 5: %word:~5%
echo middle: %word:~2,3%
echo last 4: %word:~-4%
echo drop last 4: %word:~0,-4%
echo 2nd char: %word:~1,1%first 5: Micro
from 5: soft
middle: cro
last 4: soft
drop last 4: Micro
2nd char: i
A negative start counts from the end; a negative length means "stop this many characters before the end". If you ask for more characters than exist, you simply get what's there; no error is raised.
A practical use is padding and aligning. Prepend a fixed run of spaces or zeros, then keep only the last N characters:
@echo off
set "n=7"
set "padded=000%n%"
echo invoice-%padded:~-4%
set "name=Ada"
set "col=%name% "
echo [%col:~0,10%] [end]invoice-0007
[Ada ] [end]
Search and replace: %var:old=new%
@echo off
set "path_unix=/home/ada/projects/site"
set "path_win=%path_unix:/=\%"
echo %path_win%
set "msg=I like cats. Cats are great."
echo %msg:cats=dogs%
echo %msg: =_%
echo %msg:.=%\home\ada\projects\site
I like dogs. dogs are great.
I_like_cats._Cats_are_great.
I like cats Cats are great
Note that cats=dogs also replaced Cats: the match is case-insensitive, and the replacement is inserted exactly as written. Replacing with nothing (%msg:.=%) deletes every match.
Removing a prefix with *
A * at the start of the search text matches everything up to the first occurrence. It's how you split "key=value" style data:
@echo off
set "line=user=ada@example.com"
echo value: %line:*user=%
set "email=ada@example.com"
echo domain: %email:*@=%value: =ada@example.com
domain: example.com
The first line still starts with = because only user was removed. Getting the part before a separator is easier with for /f and delims.
Testing whether a string contains text
Replace the text you're looking for with nothing; if the result differs from the original, the text was there:
@echo off
set "file=report-final.docx"
if not "%file:final=%"=="%file%" (echo contains "final") else (echo no "final")
if not "%file:draft=%"=="%file%" (echo contains "draft") else (echo no "draft")contains "final"
no "draft"
You can also pipe the value into findstr, which supports patterns: echo %file%| findstr /i "final" >nul && echo found. See findstr.
Trimming
CMD can't trim whitespace directly, but for /f "tokens=*" drops leading spaces and tabs, and the substring syntax removes trailing characters:
@echo off
set "raw= padded text"
for /f "tokens=*" %%t in ("%raw%") do set "trimmed=%%t"
echo [%raw%]
echo [%trimmed%]
set "slash=C:\data\"
if "%slash:~-1%"=="\" set "slash=%slash:~0,-1%"
echo [%slash%][ padded text]
[padded text]
[C:\data]
Length of a string
There's no length operator, so you count. The simplest approach removes one character at a time in a loop:
@echo off
set "text=Hello batch"
set "rest=%text%"
set /a len=0
:count
if defined rest (
set "rest=%rest:~1%"
set /a len+=1
goto count
)
echo "%text%" has %len% characters"Hello batch" has 11 characters
The loop works with %rest% inside a parenthesised block only because each goto count re-reads the block from scratch. In a for loop you'd need delayed expansion, explained in setlocal & Delayed Expansion.
Upper and lower case
Because replacement is case-insensitive but inserts the replacement as written, replacing each letter with its upper-case form converts the whole string:
@echo off
set "s=Batch Is Fun"
for %%L in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do call set "s=%%s:%%L=%%L%%"
echo %s%BATCH IS FUN
call set forces a second round of expansion so the loop letter %%L can be used inside the %s:...% syntax. With delayed expansion you'd write set "s=!s:%%L=%%L!", which is faster.
Variables inside the substring syntax
The positions in %var:~start,len% must be literal numbers. To use a variable as a position, you need a second round of expansion, either with call or with delayed expansion:
@echo off
setlocal enabledelayedexpansion
set "alphabet=ABCDEFGHIJ"
set /a pos=3, size=4
echo !alphabet:~%pos%,%size%!
call echo %%alphabet:~%pos%,%size%%%DEFG
DEFG
Comparison with other shells
| Task | CMD | Bash | PowerShell |
|---|---|---|---|
| substring | %s:~2,3% |
${s:2:3} |
$s.Substring(2,3) |
| replace | %s:a=b% |
${s//a/b} |
$s -replace 'a','b' |
| last 4 chars | %s:~-4% |
${s: -4} |
$s.Substring($s.Length-4) |
| length | a loop | ${#s} |
$s.Length |
Learn more: Bash Strings, PowerShell Strings, for /f: Parse Text.
Test yourself
With set "v=abcdef", what does %v:~1,3% give?
- abc
- bcd
- bc
- cde
What does %v:~-2% return for v=report.txt?
- re
- xt
- report.t
- txt
With set "s=Red red RED", what does echo %s:red=blue% print?
- Red blue RED
- blue blue blue
- Blue blue BLUE
- Red red RED