user767990
user767990

Reputation: 115

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

Upvotes: 8

Views: 7206

Answers (3)

Carey Gregory
Carey Gregory

Reputation: 6846

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

Upvotes: 3

jeb
jeb

Reputation: 82307

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

Upvotes: 4

walid2mi
walid2mi

Reputation: 2888

 @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

Upvotes: 14

Related Questions