Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge 2 txt files in a single tab delimited file in batch

I'm stuck with this : I need to merge two text files in a single tab delimited text file, on a batch script. ex :

file1:

qwer
tyui
asdf

file2:

1345
6876
8796

file3:

qwer    1345
tyui    6876
asdf    8796

All I need in fact, is a equivalent to Unix command : paste -d "\t" file1 file2 > file3

like image 545
user767990 Avatar asked Aug 11 '11 19:08

user767990


People also ask

How do I combine multiple text files into one?

Two quick options for combining text files. Open the two files you want to merge. Select all text (Command+A/Ctrl+A) from one document, then paste it into the new document (Command+V/Ctrl+V). Repeat steps for the second document.

How do I concatenate text files in Windows?

In the Word Ribbon, click the Insert tab, click the down arrow next to Object, and select the Text from File option, as shown below. Select the file you want to merge into the current document and click Insert. Once completed, the text and other information from the document will be merged into the current document.


3 Answers

 @echo off

 set f1=1.txt
 set f2=2.txt
 set "sep=  "  % tab %

 (
   for /f "delims=" %%a in (%f1%) do (
      setlocal enabledelayedexpansion
       set /p line=
       echo(%%a!sep!!line!
      endlocal
   )
 )<%f2%

pause
goto :eof
like image 118
walid2mi Avatar answered Nov 03 '22 09:11

walid2mi


The answer of walid2me is awesome, this is only a small mofication to show how to make it safe against characters like !^ in the file 1.txt, the content of file 2.txt is safe, a it is read with teh set/p syntax.

@echo off

 set f1=1.txt
 set f2=2.txt
 set "sep=  "  % tab %

 (
   setlocal DisableDelayedExpansion
   for /f "delims=" %%a in (%f1%) do (
      set "f1_line=%%a"
      setlocal EnableDelayedExpansion
       set /p f2_line=
       echo(!f1_line!!sep!!f2_line!
      endlocal
   )
   endlocal
 )<%f2%

pause
goto :eof

As you can see, I only move the expansion of %%a just before the setlocal EnableDelayedExpansion

There is still another small flaw, as set/p strips trailing control characters, like single CR, LF and also TAB.
This affects only the file 2.txt.

In depth analysis about set /p are at New technic: set /p can read multiple lines from a file

like image 41
jeb Avatar answered Nov 03 '22 10:11

jeb


There's no native Windows command I know of that will do that, but there's a set of Unix tools for Windows here.

like image 30
Carey Gregory Avatar answered Nov 03 '22 09:11

Carey Gregory