Ein Kollege wollte vor einiger Zeit von mir ein kleines Programm, das nur aus einer Textdatei ein bestimmtes Wort aus einer bestimmten Zeile liest. Damit wurde beim Kunden dann ein Server konfiguriert. Auf meinen Einwand hin, dass man dafür kein Programm, sondern nur die Shell von Windows benötigt, kam ein "haben wir schon probiert, geht nicht" zurück. Damit war mein Ehrgeiz geweckt :-) Es hat etwas Probieren gekostet und ich finde den Code noch nicht "schön", aber er läuft. Wer also aus einer Eingabedatei das 8. wort aus der 42. Zeile benötigt, findet hier das Script dazu. Viel Spass damit!
@echo off
:: select token from input file
:: (c) 2003 Armin Hanisch -- www.ArminHanisch.de
:: %1 filename
:: %2 line no
:: %3 word no
if x%1 == x goto usage
if x%1 == x!!! (goto doit) else (set line=0)
if not exist %1 goto nofile
:: add the delims= option between the quotes, if your input is
:: not separated by white space, e.g. for /F "tokens=%3 delims=;" .....
for /F "tokens=%3" %%f in (%1) do @call %0 !!! %2 %%f
set line=
goto eof
:doit
set /a line="%line%+1"
if %2 == %line% echo %3
goto eof
:usage
echo %0 - extract a word from a text input file
echo Copyright (c) 2003 by Armin Hanisch
echo.
echo Usage: %0 [filename] [line#] [word#]
echo.
echo Words in input file are separated by white space.
echo If you need different delimiters, check the code for help.
echo.
goto eof
:nofile
echo Could not find input file %1 - terminating.
goto eof
:eof
:: -------- delete this after you understand how it works :-) --------
::
:: this batch uses self-execution so we just need one batch file.
:: but for this we have to know if we just called us, so the first line
:: of code checks for the first parameter being "!!!". Keep in mind that
:: you cannot have an input named named like this test string!
:: if we do not find the test marker, we set an env var to the start
:: value of zero, as we have processed zero lines up to now.
:: Now we loop thru the input file, extracting the specified word number
:: (by using the token= option for the FOR command). The catch calls
:: itself and after the "!!!" marker send the desired line number and
:: the current word number %3, then jumps to the label ":doit"
:: here we increment the line count using SET's /a option. If the line
:: numbers match up we found the desired line and just ouput the word.
:: if you find it useful, why not visit one of my Windows shell trainings?
:: check out my home page for my current employer CTEC and contact data.