开发者

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 d开发者_运维百科elimited 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


 @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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜