How to extract text before a character or string in a batch file

batchcmd.execommand line

I'm basically looking for the opposate of this post: https://stackoverflow.com/questions/47796707/how-to-extract-text-after-in-batch-file. I'm looking to extract the text before an equal sign in a string of text (or remove the text after the equal sign and the equal sign).

Example Input:

User=Your Friend

Desired Output:

User

Since the length of the text before and after the equal sign varies I cant use something like %var:~0,-12%.

Best Answer

I'm looking to extract the text before an equal sign in a string of text

Use the following batch file (test.cmd):

@echo off
setlocal enabledelayedexpansion
set _string=User=Your Friend
echo %_string%
for /f "tokens=1 delims==" %%a in ("%_string%") do (
  echo %%a
  )
endlocal

Example output:

> test
User=Your Friend
User

Further Reading

Related Question