Combining multiple text files into one

I have searched high and low level world wide web and don't seem to find a solution for my problem! I have several text files that I would like to combine.

It is easier to show examples than to explain exactly why I am trying to do this.

The first file looks like this:

John
Paul
Mark
Sam
Herold

      

This file serves as the "primary key".

The rest of the files contain data for each item like this. The program generates this data into a new file every hour.

4
10
20
5
200

      

I am most into Windows batch files, so I tried to write something like this:

for /f "tokens=*" %%A in (file1.txt) do 
    (for /f "tokens=*" %%B in (file2.txt) do (echo %%A,%%B>>combined.txt))

      

Unfortunately, every value records every value. If it works as expected, the end result is:

John,4,2,6,9,1,2,5,6,12,51,53,3,6,7,8,1,4,7,2,743,21,4,7,5
Paul,10,5,6,1,7,9,34,56,1,76,48,23,222,12,54,67,23,652,1,6,71,3,6,4

      

etc.

The software I am using presents data in this format and cannot be modified. I am open to any suggestions.

+2


source to share


3 answers


You can read multiple input files in a batch program through standard descriptors. Remember 0 is Stdin, 1 is Stdout and 2 is Stderr, but this leaves handles 3 to 9 available! The batch file below merges files with the contents of two files; of course up to 8 files can be combined with this method.

@echo off
setlocal EnableDelayedExpansion
Rem First file is read with FOR /F command
Rem Second file is read via standard handle 3
3< file2.txt (for /F "delims=" %%a in (file1.txt) do (
   Rem Read next line from file2.txt
   set /P line2=<&3
   Rem Echo lines of both files
   echo %%a,!line2!
))

      



More details here: http://www.dostips.com/forum/viewtopic.php?f=3&t=3126

+9


source


The unix paste command might be what you are looking for. See also fooobar.com/questions/2044491 / ... .



+1


source


You can simply do:

paste -d, file*.txt > combined.txt

      

if you have paste

. You may need to install cygwin or work on a * nix machine. (You said you were open to all suggestions!) It depends on the sequences of the data files. If you want to customize the order, you can write it down instead of using glob.

+1


source







All Articles