Merge two file in a new one

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Merge two file in a new one

#1 Post by darioit » 21 Aug 2020 06:22

Hello, I try to solve in many way this problem without success, maybe you have the solution
my goal is merge file a.txt and b.txt into new one, read first file and if first item is present in second file update it in c.txt file, if not just copy row from a.txt to c.txt

first file

a.txt
AAA;2020-09-01;Y
BBB;2020-09-01;Y
CCC;2020-09-01;Y

second file

b.txt
AAA;2020-09-01;Y;21/08/2020
BBB;2020-09-01;Y

results:

c.txt
AAA;2020-09-01;Y;21/08/2020
BBB;2020-09-01;Y
CCC;2020-09-01;Y

Thank you in advance

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Merge two file in a new one

#2 Post by aGerman » 21 Aug 2020 07:21

Code: Select all

>"c.txt" (
  for /f "usebackq delims=" %%i in ("a.txt") do (
    set "line="
    for /f "delims=" %%j in ('findstr /b "%%i" "b.txt"') do set "line=%%j"
    if defined line (
      setlocal EnableDelayedExpansion
      echo(!line!
      endlocal
    ) else echo(%%i
  )
)
This should give you the desired result at least for your example.

Steffen

darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Re: Merge two file in a new one

#3 Post by darioit » 03 Sep 2020 04:00

Many thank works fine, I had another problem, I use this command "findstr /livg:" for merge two file in a new one in both direction, but command FAIL if a second file is empty, how can I solve this problem?

a.txt
1st_file_1st_row
2nd_file_2st_row
1st_file_3st_row
1st_file_4st_row
1st_file_4st_row
1st_file_5st_row

b.txt
1st_file_1st_row
1st_file_2st_row
1st_file_3st_row
1st_file_4st_row
2st_file_4st_row
1st_file_5st_row

Code: Select all

findstr /livg:a.txt b.txt > ab.txt
ab.txt
1st_file_2st_row
2st_file_4st_row

Code: Select all

findstr /livg:b.txt a.txt > ba.txt
ba.txt
2nd_file_2st_row

if b.txt is empty I got a ab.txt empty, but I want all line from a.txt (same problem in reverse condition)

thank you in advance

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Merge two file in a new one

#4 Post by aGerman » 03 Sep 2020 15:33

I think you can just determine the file size (modifier ~z of a FOR variable). If it is zero then copy the other file.

Steffen

darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Re: Merge two file in a new one

#5 Post by darioit » 04 Sep 2020 00:03

I thought about it, if empty just copy

Thanks
Dario

Post Reply