Page 1 of 1

Read line from two text files and make output

Posted: 22 Apr 2019 05:49
by sincos2007
Hi,

What I want is described in following pseudo code:

Code: Select all

file1=openfile in1.txt
file2=openfile in2.txt
file_out=openfile out.txt

while not file1.EOF and not file2.EOF
{ // in each loop, read next line from file1 and file2
   line_in_file1=file1.ReadLine
   line_in_file2=file2.ReadLine
   
   // two lines are not same 
   if line_in_file1 <> line_in_file2
   {
      // line_in_file1 and line_in_file2 are made into
      // one line and append the line to end of out.txt
      file_out.append_line( line_in_file1 & line_in_file2 )
   }
}

close file1
close file2
close file_out
How to implement above function in batch file?

Thanks

Re: Read line from two text files and make output

Posted: 22 Apr 2019 06:54
by aGerman
Provided both files have the same number of lines:

Code: Select all

@echo off

setlocal DisableDelayedExpansion
set "in_file1=txt1.txt"
set "in_file2=txt2.txt"
set "out_file=out.txt"

<"%in_file1%" >"%out_file%" (
  for /f "delims=" %%i in ('findstr /n "^" "%in_file2%"') do (
    set "line2=%%i"

    setlocal EnableDelayedExpansion
    set "line1=" &set /p "line1="
    if "!line1!" neq "!line2:*:=!" (
      for /f "delims=:" %%j in ("!line2!") do echo line %%j: !line1! ^<--^> !line2:*:=!
    )
    endlocal
  )
)

Steffen

Re: Read line from two text files and make output

Posted: 25 Apr 2019 12:47
by sincos2007
Hi Steffen,

I notice that you use command “findstr /n” to list lines in second input file with line number at start of each line. And when you do comparing two lines, you remove “:” and any characters before this “:” from each line in second input file.

A moment ago, I get why you use “/n” to list line number. You use this number for line number in result output.

The code works fine and it is useful skill

By the way, could you introduce some tutorials on internet or books about batch programming to me, which may be helpful to me in the future.

Thanks

Re: Read line from two text files and make output

Posted: 25 Apr 2019 14:30
by aGerman
sincos2007 wrote:
25 Apr 2019 12:47
A moment ago, I get why you use “/n” to list line number. You use this number for line number in result output.
Outputting the line number is rather an incidental. There is another reason. You can't prevent the FOR /F loop from ignoring empty lines if you read the file directly. As soon as you parse the output of FINDSTR /N, even an empty line isn't empty anymore. It contains at least the line number and the colon.

Steffen

Re: Read line from two text files and make output

Posted: 25 Apr 2019 15:33
by sincos2007
Good idea.