I have a text file with n number of rows. m number of the rows contain a string that I'm interested in (m<=n). I need a batch file that will copy only a single row (e.g. the first occurance) containing the string to a new text file. When I use the findstr command it will copy all rows containing the string.
Thanks! Paul Safier
Given your FINDSTR command that locates your m rows (it can be as simple or as complicated as you need)
findstr "search" "fileName.txt"
then you can process the results of that command with a FOR /F loop. You can break out of the loop after the first matching line by using GOTO.
for /f "delims=" %%A in ('findstr "search" "fileName.txt"') do (
echo %%A >>"outFile.txt"
goto :break
)
:break
The FOR command is one of the more complicated commands available to batch. There are many options. You can get help on the command by typing HELP FOR
or FOR /?
from a command prompt.
The "DELIMS=" option disables the parsing of the line into tokens. Without that option, the FOR /F would break each line into tokens, delimited by space or tab characters. The list of delimiters can be set to other caracter(s), or in your case, set to nothing.
The code I gave above will skip lines that begin with ;
because FOR /F will skip any lines that begin with the EOL character - ;
by default. You can change the EOL character to any single character. But if you don't know what your matching line might start with, then you don't know what character to use for EOL. The syntax to completely disable all token parsing and EOL line skipping is odd:
for /f delims^=^ eol^= %%A in (...) do ...