If your file only has 19 lines, then you only want to keep line 2. The easiest solution is to flip the logic and worry about the line you want to keep.
Here are a few options for extracting the 2nd line.
This one is limited to a maximum line length of 1021, and trailing control characters will be stripped.
@echo off
setlocal enableDelayedExpansion
set "csv=test.csv"
<"%csv%" (
set /p "ln="
set /p "ln="
)
(echo(!ln!)>"%csv%"
Use of a FOR /F supports line lengths up to nearly 8191.
@echo off
setlocal
set "csv=test.csv"
for /f "usebackq skip=1 delims=" %%A in ("%csv%") do (
(echo(%%A)>"%csv%"
goto :break
)
:break
If you know that your target line does not begin with :
, then
@echo off
setlocal
set "csv=test.csv"
for /f "tokens=1* delims=:" %%A in (
'findstr /n "^" "%csv%" ^| findstr /b "2:"'
) do (echo(%%B)>"%csv%"
EDIT
Now that I know the source file has more than 19 lines, than I would use Stephan's answer, unless one of the following limitations becomes a problem:
- SET /P cannot read more than 1021 characters in a line
- MORE will convert tabs into a string of spaces
- If the file is large enough (I think more than 64K lines) then the output will eventually hang, waiting for a key press, even though the MORE output is redirected.
IF any of the above limitations are a problem, and all lines are less than 8191 characters long, and no line begins with :
, then the following will work. But it is slower.
@echo off
setlocal
set "csv=test.csv"
>"%csv%.new" (
for /f "tokens=1* delims=:" %%A in ('findstr /n "^" "%csv%"') do (
if %%A equ 2 echo(%%B
if %%A gtr 19 echo(%%B
)
)
move /y "%csv%.new" "%csv%" >nul
But if you want a really fast solution without any restrictions, then you could use my REPL.BAT utility - a hybrid JScript/batch script that performs a regex search/replace operation on stdin and writes the result to stdout. It is pure script that will run natively on any modern Windows machine from XP onward. Full documentation is embedded within the script.
@echo off
setlocal
set "csv=test.csv"
findstr /n "^" "%csv%"|repl "^(1|10|11|12|1?[3456789]):" ":"|repl "^\d+:" "" A >"%csv%.new"
move /y "%csv%.new" "%csv%" >nul
The initial FINDSTR simply prefixes each line with the line number, followed by a colon.
The first REPL strips the line number before the colon if it is 1 or 3-19
The last REPL removes any prefix beginning with a number followed by a colon, and discards lines that are not modified.