Batch file to merge two column strings from two files into one file

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
goodywp
Posts: 250
Joined: 31 Jul 2017 09:57

Batch file to merge two column strings from two files into one file

#1 Post by goodywp » 14 Feb 2022 09:32

HI All,.

I have been searched up for a batch scripts solution to do the below job:
file1.txt which has strings listed as below
"12345"
"23456"
"34567"
"45678"

file2.txt
"abcde"
"bcdef"
"cdefg"
"defgh"

Now I would like to merge this two files as one file, in this file the two list of strings also merged as below

"12345" "abcde"
"23456" "bcdef"
"34567" "cdefg"
"45678" "defgh"

I know there are some other language can do this job easier than batch scripts. Can we do this in batch?

Squashman
Expert
Posts: 4465
Joined: 23 Dec 2011 13:59

Re: Batch file to merge two column strings from two files into one file

#2 Post by Squashman » 14 Feb 2022 11:36

Code: Select all

@echo off
setlocal enabledelayedexpansion
< file2.txt ( FOR /F "delims=" %%G IN (file1.txt) DO (
set /p file2=
echo %%G !file2!
)
)>combined.txt

goodywp
Posts: 250
Joined: 31 Jul 2017 09:57

Re: Batch file to merge two column strings from two files into one file

#3 Post by goodywp » 14 Feb 2022 13:25

Thanks a lot! This is the simplest code ever I see for this solution. Just added the space between

Code: Select all

@echo off
setlocal enabledelayedexpansion
< file2.txt ( FOR /F "delims=" %%G IN (file1.txt) DO (
set /p file2=
echo %%G !file2!
)
)>combined.txt

penpen
Expert
Posts: 1991
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Batch file to merge two column strings from two files into one file

#4 Post by penpen » 15 Feb 2022 08:10

Just wanted to mention that you might get unwanted results, if your example is not representative.

In SQL terms (which is the easiest to describe a possible issue):
If you assume the line number to be the related column to join, then the the solution is a natural inner join.
If that is, what you want, then all is OK, else if "file1.txt" has fewer lines than "file2.txt", then you will lose some lines.


penpen

goodywp
Posts: 250
Joined: 31 Jul 2017 09:57

Re: Batch file to merge two column strings from two files into one file

#5 Post by goodywp » 15 Feb 2022 14:52

Thanks Penpen for your input! I have exactly number of lines in each files.

Post Reply