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 WS2I 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).
21 Answer
A simple solution is
for /f "tokens=3" %%a in (database.txt) do set word3=%%aAfter 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.