How to read multiple files at once?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
miskox
Posts: 668
Joined: 28 Jun 2010 03:46

How to read multiple files at once?

#1 Post by miskox » 13 Sep 2012 06:33

Hi all,

let's say I have two (or more) txt files:

FILE1.TXT

Code: Select all

A
B
C
D


FILE2.TXT

Code: Select all

1
2
3
4


OUTPUT_FILE.txt

Code: Select all

A1
B2
C3
D4



I would like to:

1. open file1.txt for read
2. open file2.txt for read
3. open output_file.txt for write
4. read first record from file1
5. read first record from file2
6. make new output string: record from 1st file+record from 2nd file
7. write new output string
8. goto 4

First let's say that number of records in both files are the same. Next problem would be to be ignore missing records from each file.

If I use

Code: Select all

for /f %%a
for /f %%b


it first completes loop %%b and then %%b.

Thanks.

Any ideas?
Saso

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: How to read multiple files at once?

#2 Post by abc0502 » 13 Sep 2012 06:47

I had this problem before

Code: Select all

@echo off & cls
set "file1=file1.txt"
set "file2=file2.txt"
set "separator= "

 (
   for /f "delims=" %%a in (%file1%) do (
      setlocal enabledelayedexpansion
         set /p line=
         echo.%%a!separator!!line!
      endlocal
   )
 )<%file2%>>"out.txt"


but this limited to two files, but you can make it as a function that take three parameters, infile1, infile2 and outfie
and then use call to call the function and pass the parameters, that what i did. :)

miskox
Posts: 668
Joined: 28 Jun 2010 03:46

Re: How to read multiple files at once?

#3 Post by miskox » 13 Sep 2012 12:19

Thank you.

I will try this later/tomorrow.
Anyway I can call this procedure twice (or more) if I have three or four files (or more).

Saso

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: How to read multiple files at once?

#4 Post by abc0502 » 13 Sep 2012 12:40

miskox wrote:I will try this later/tomorrow.
Anyway I can call this procedure twice (or more) if I have three or four files (or more).

Exactly, but to keep the code clean you should make it as a function like this:

Code: Select all

@echo off & cls

Call :merge "file1.txt" "file2.txt" "/" "output.txt"
Call :mereg "filex1.txt" "filex2.txt" ":" "outx.txt"
pause

:merge
set "in1=%~1"
set "in2=%~2"
set "sep=%~3"
set "out=%~4"

 (
   for /f "delims=" %%a in (%in1%) do (
      setlocal enabledelayedexpansion
         set /p line=
         echo.%%a!sep!!line!
      endlocal
   )
 )<%in2%>>"%out%"
goto :eof


and to mereg more files just keep calling the function

Post Reply