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|
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
I need the new file to look like this (line 1):
13CT162|\\TEST-CLER\COMPLETE\13CT162.tif
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!!
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
Edit: 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
来源:https://stackoverflow.com/questions/25392759/how-to-concatenate-corresponding-lines-in-two-text-files