windows 批量合并单个制表符分隔文件中的 2 个 txt 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7031687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:48:57  来源:igfitidea点击:

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

windowsbashbatch-file

提问by user767990

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:

文件 1:

qwer
tyui
asdf

file2:

文件2:

1345
6876
8796

file3:

文件 3:

qwer    1345
tyui    6876
asdf    8796

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

事实上,我只需要一个等价于 Unix 命令的命令: paste -d "\t" file1 file2 > file3

回答by walid2mi

 @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

回答by Carey Gregory

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

有没有原生Windows命令我知道,这将做到这一点,但有一个用于Windows的一套Unix工具在这里

回答by jeb

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.txtis safe, a it is read with teh set/psyntax.

walid2me 的答案很棒,这只是一个小小的修改,展示了如何使它对!^文件中的字符安全,文件1.txt的内容2.txt是安全的,它是用set/p语法读取的。

@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 %%ajust before the setlocal EnableDelayedExpansion

如您所见,我只%%asetlocal EnableDelayedExpansion

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

还有另一个小缺陷,如set/p删除尾随控制字符,如单个 CR、LF 和 TAB。
这仅影响文件 2.txt。

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

在深入分析大约set /p是在新工艺:集/ p可以从文件中读取多行