0
votes

I have to combine csv files into 1 file using a batch file.

The problem is that I only need the third row from each file.

How can I extract a specific row from a csv file in the windows command line / batch file?

I have found skip as command to skip lines from start of file, but I need to also skip the files from after the line I need.

This is my current code (after converting from xls to csv):

for %%i in (headers.csv) do (
    for /f "delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
)
for %%i in (file*.csv) do (
    for /f "skip=2 delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
)
2
Do you only need row3 of one line or does the csv contain multiple lines you need? - BaBa
I needed the first line (headers) and then the third line of the first file. And then only the third line of every other file, since we already have the headers. I went around that by creating a seperate file for the headers. And now all I needed was the third line. Both answers below solved my problem. Thank you for replying though! - LvS

2 Answers

1
votes
for %%i in (headers.csv) do (
 set "flag=Y"
 for /f "delims=" %%j in ('type "%%i"') do if defined flag set "flag="&echo %%j >> combined.csv
)
for %%i in (file*.csv) do (
 set "flag=Y"
 for /f "skip=2 delims=" %%j in ('type "%%i"') do if defined flag set "flag="&echo %%j >> combined.csv
)

flag is set to something each time a new file is chosen. The first 2 lines of that file are then skipped, and on the third flag is cleared and the line reproduced. Once flag is cleared (becomed not-defined) the echo won't happen.

if defined works on the current (ie run-time) value of the variable, not the initial (parse-time) value.

1
votes
@echo off
    setlocal enableextensions disabledelayedexpansion

    (
        for /f "tokens=1,* delims=:" %%a in ('
            findstr /n "^" headers.csv file*.csv ^| findstr /r /c:"^[^:]*:3:"
        ') do (
            set "line=%%b"
            setlocal enabledelayedexpansion
            echo(!line:~2!
            endlocal
        )
    ) > combined.csv

It will use findstr to retrieve the full content from all the indicated files (I was not sure and I've also included the headers file), with lines numbered. As multiple files are requested, the output from this first findstr command will be in the format

filename.ext:lineNumber:linedata

This is filtered by a second findstr using a regular expression to only retrieve the third line from each file.

These lines will be processed by the for loop, using the colon as a delimiter to remove the file name. To avoid problems with lines that could start with a colon, the line number and the aditional colon are removed with a substring operation.

If in the final code the reference to the files forces findstr to include in the output the full path to the files, the tokens clause needs to be changed to tokens=2,* to face the colon in the drive name.