如何串联两个文本文件中的相应行 [英] How to concatenate corresponding lines in two text files

查看:125
本文介绍了如何串联两个文本文件中的相应行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要合并两个文本文件,方法是将文件#2的第n行连接到文件#1的第n行以合并文件#3的第n行.它们将始终具有相同的行数并始终匹配(即,一个文件中的第1行与第二个文件中的第1行匹配).我必须将这两个文件串联成一个新的第三个文件.字段之间未添加空格.我正在运行Windows 7并使用批处理文件,但如果这里更好的选择,我可以使用Powershell.这是第一个名为test.txt的文件的示例:

I have two text files that I need to combine by concatenating line n from file #2 to line n of file #1 to make line n of file #3. They will always have the same number of lines and will always match up (i.e. line 1 in one file is a match to line 1 in the second file). I have to concatenate these two files into a new, third file. No spaces added between the fields. I am running Windows 7 and using a batch file but I could use powershell if that’s a better choice here. Here's an example of the first file named test.txt:

13CT162| 
13MM1364 VOP AFF| 
13MM1872| 
14ct70| 
Another| 
brake f_Page_1|
brake f_Page_2| 
brake f_Page_3| 
brake f_Page_4| 
brake f_Page_5|

这是第二个名为Index1.txt的文件中的相应信息:

Here's the corresponding info from the second file named Index1.txt:

\\TEST-CLER\COMPLETE\13CT162.tif
\\TEST-CLER\COMPLETE\13MM1364 VOP AFF.tif
\\TEST-CLER\COMPLETE\13MM1872.tif
\\TEST-CLER\COMPLETE\14ct70.tif
\\TEST-CLER\COMPLETE\Another.tif
\\TEST-CLER\COMPLETE\brake f_Page_1.tif
\\TEST-CLER\COMPLETE\brake f_Page_2.tif
\\TEST-CLER\COMPLETE\brake f_Page_3.tif

\\TEST-CLER\COMPLETE\brake f_Page_4.tif
\\TEST-CLER\COMPLETE\brake f_Page_5.tif

我需要新文件看起来像这样(第1行):

I need the new file to look like this (line 1):

13CT162|\\TEST-CLER\COMPLETE\13CT162.tif

对于如何附加文件,我可以找到很多帮助,但是如何将两个文件串联到第三文件中却很少.这里有一个现成的答案,但这是针对Python的.我必须使用Win 7 cmd或powershell命令.在此先感谢!

I can find lots of help on how to append the files but little on how to concatenate two files into a third one. There is an existing answer here but it is for Python. I have to use Win 7 cmd or powershell commands. Thanks in advance!!

推荐答案

您可以使用For循环在PowerShell中执行此操作:

You can use a For loop to do this in PowerShell:

$File1 = Get-Content C:\Path\To\File1.txt
$File2 = Get-Content C:\Path\To\File2.txt
$File3 = @()
For($a=0;$a -lt $File1.count;$a++){
    $File3+=$File1[$a].trim()+$File2[$a].trim()
}
$File3 | Out-File C:\Path\To\NewFile.txt

编辑:好的,我没有想到单行文件.这将使$ File1和/或$ File2字符串代替数组.我们可以很容易地使它们成为数组,以便可以正确地索引它们:

Ok, I didn't think of single line files. That would make $File1 and/or $File2 strings instead of arrays. We can make them arrays easily enough so it can properly index into them:

$File1 = @((Get-Content C:\Path\To\File1.txt))
$File2 = @((Get-Content C:\Path\To\File2.txt))
$File3 = @()
For($a=0;$a -lt $File1.count;$a++){
    $File3+=$File1[$a].trim()+$File2[$a].trim()
}
$File3 | Out-File C:\Path\To\NewFile.txt

这篇关于如何串联两个文本文件中的相应行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆