Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining multiple text files into one

I have searched the world wide web high and low, and can't seem to find any solution for my problem! I have multiple text files that I would like to combine.

It's easier to show examples than to explain exactly why I'm trying to do.

The first file looks like this:

John
Paul
Mark
Sam
Herold

This file serves as a "primary key".

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

4
10
20
5
200

I'm most familiar with 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 that writes every value to every person. If this would be working as expected, the end result would be like this:

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

and so on.

The software I am using presents the data in this format, and cannot be changed. I am open to any and all suggestions.

like image 662
bonneyt Avatar asked Oct 21 '25 12:10

bonneyt


2 Answers

You may read several input files in a Batch program via the standard handles. Remember that 0 is Stdin, 1 is Stdout and 2 is Stderr, but this leaves handles 3 to 9 available! The Batch file below do a file merge 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!
))

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

like image 52
Aacini Avatar answered Oct 24 '25 13:10

Aacini


The unix command paste maybe what you're looking for. Also see this question on StackOverflow.

like image 20
Jannik Jochem Avatar answered Oct 24 '25 11:10

Jannik Jochem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!