Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

extracting specific lines of data from multiple text files, to convert to a single csv file

First, apologies for my poor coding ability, however I have spent a few hours reading the forums and giving it a crack, so I would really appreciate any help with the following problem:

I have 3 text files, from which I would like to take the filename, 3rd line of data, 5th line, and 7th line and pop them into a single CSV, such as follows:

filename1, linedata3, linedata5, linedata7
filename2, linedata3, linedata5, linedata7
filename3, linedata3, linedata5, linedata7

Simples, eh? not so, for I am rather lacking in my coding "skillz" and could do with your help. Here's what I have so far:

First a batch file (go.bat):

@echo off
for /f "skip=2 delims=" %%i in (%1) do >>lines.txt echo %~n1 %%i & goto :EOF

Then manual command line entries:

go.bat file1.txt
go.bat file2.txt
go.bat file3.txt

So, as you can see, I have done this for one line of text, but don't know how to append lines 3 and 5 onto the end of the output. Also, what I'd really like is a proper command line entry so I can do this for all text files in the directory. I tried the following, but seem to be missing something:

for %i in (*.*) do go.bat "%i"

Any body help?

Thanks muchlies! James

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
@echo off
setlocal EnableDelayedExpansion
if exist result.csv del result.csv
for %%f in (*.txt) do (
    set i=0
    for /F "delims=" %%l in (%%f) do (
        set /A i+=1
        set line!i!=%%l
    )
    echo %%f, !line3!, !line5!, !line7! >> result.csv
)

This Batch file process all .txt files in the directory, as you said.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...