How do i output the first word in text file?

March 25, 2011 at 15:34:57
Specs: Windows Vista
i'm trying to write a batch file that sets a variable to the first word in a text file.
i can get it to find the first word in the text file using the findstr command, but it outputs the entire line, this is what i have so far:

@echo off
for /f "tokens=*" %%a in ('findstr /b /i "\<.*\>" "%cd%\somthing.txt"') do set a=%%a
echo %a%

but even though it is picking up on the first word, it outputs the whole line, and i can't find any commands to make it output just the first word.
does anyone have an idea of how to make this output the first word? or possibly even a completely new command to do so. thanks a heap for any suggestions :)

See More: How do i output the first word in text file?

Report •

March 25, 2011 at 19:58:58
The first "word" in the file:

@echo off
for /f "usebackq" %%a in ( "filename" ) do (
    set a=%%a
    goto done
echo %a%

Report •

March 25, 2011 at 20:19:52
Wow, that works perfectly, i don't quite understand how it works though, it doesn't give a very good description of the usebackq command in for /?, so if it's not too much trouble could you please explain how it works.
thanks for the helping!

Report •

March 25, 2011 at 20:27:42
usebackq changes the quoting scheme that the "in" part uses, double quotes normally mean a string and no quotes a file name.

If the file name has(or could have) a space in it then you need to double quote the file name, usebackq changes the meaning of the double quotes from "a string" to "a filename".

The tokens and delims are not specified so they default tokens to "1" and delims to a space and a tab.

Report •

Related Solutions

March 25, 2011 at 20:32:34
i have also just figured out, using that, another way of doing it, if you change the code to:

@echo off
for /f "tokens=1" %%a in ('findstr /i "\<.*\>" "%cd%\somthing.txt"') do set a=%%a
echo %a%

and simply make the tokens =1 then it returns the first word, and you can change it to tokens =2 to get it to return the 2nd word and so on,
Thanks again! :)

Report •

March 25, 2011 at 20:40:27
In addition to #3 I should mention that usebackq also changes single quotes to 'a string' from 'a command' and back quotes to `a command`.

Report •

March 27, 2011 at 16:02:42
Thats a useful information on usebackq.. Thanks Judago. :)

Subhash Chandra.

Report •

Ask Question