Celeb Glow
general | March 16, 2026

Batch to extract a word from a string inside a text file

I have a database.txt file with this content:

40001 16 DATAMAN Jimbo WS2

I want to extract the third word, as delimited by whitespace ("DATAMAN" in this example), and store it in a variable in a Windows batch script. The length of whitespace can vary (as can the length of the word).

2

1 Answer

A simple solution is

for /f "tokens=3" %%a in (database.txt) do set word3=%%a

After this statement, the variable %word3% will contain the third word from the line in the file.  If the file has more than one line, you will get the third word from the last line that has at least three words; the set word3=%%a command (after the do keyword) will be executed with %%a set to the third word from each such line.  If you decide that you want to do more than one command per line, use the following syntax:

for /f "tokens=3" %%a in (database.txt) do (
     
     commands referencing %%a
     
)


Edit: As stated above, the code (commands) in the block following the do gets executed for every qualifying line.  If you want to “catch” only the first such line, you can do this by simply adding filtering logic, as in:

setlocal enabledelayedexpansion
set first=1
for /f "tokens=3" %%a in (database.txt) do (
      if !first! == 1 (
           set first=0
            
           commands referencing %%a
            
      )
)


You can replace the a (in %%a) with any letter, but it must be only a single letter; it’s not a normal variable.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy