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

1

2

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).

Luca

Posted 2013-10-30T17:55:17.453

Reputation: 25

1What world are you in, Windows or Unix? If Windows, do you have access to Unix-like tools (e.g., Cygwin)? – Scott – 2013-10-30T22:58:08.910

i'm on a Windows 7 64 bit, and i must use as less third-part softwares as possible. – Luca – 2013-10-31T14:46:28.997

Answers

2

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.

Scott

Posted 2013-10-30T17:55:17.453

Reputation: 17 653

Yeah Great, but...so, how should I do, if i want to catch the third word from the first line inside an n-lined *.ini file?? – Luca – 2013-11-04T18:42:59.880

Yeah, I added that. – Scott – 2013-11-04T21:38:08.883