问题
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
回答1:
@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.
回答2:
You could read the lines with another construct.
setlocal EnableDelayedExpansion
< %1 (
Set /p line1=
Set /p line2=
Set /p line3=
Set /p line4=
Set /p line5=
Set /p line6=
Set /p line7=
)
Echo %1,!line3!,!line5!,!line7!
Or with a loop (Andriy)
Setlocal EnableDelayedExpansion
<%1 (
For /L %%n in (1 1 7) do (
Set /p line%%n=
)
)
Echo %1,!line3!,!line5!,!line7!
来源:https://stackoverflow.com/questions/7851018/extracting-specific-lines-of-data-from-multiple-text-files-to-convert-to-a-sing