Page 1 of 1

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

Posted: 14 Feb 2022 09:32
by goodywp
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?

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

Posted: 14 Feb 2022 11:36
by Squashman

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

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

Posted: 14 Feb 2022 13:25
by goodywp
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

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

Posted: 15 Feb 2022 08:10
by penpen
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

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

Posted: 15 Feb 2022 14:52
by goodywp
Thanks Penpen for your input! I have exactly number of lines in each files.