我正在寻找一个批处理命令文件(或自动热键)解决方案,以帮助我合并两个巨大的.txt文件,它们在每行开头共享一个共同的单词,将第二个文件行的第二部分附加到第一个文件的每一行的末尾,只有当两个文件中的第一个单词完全匹配时,才能将结果输出到第三个文件中。
我环顾四周,发现了类似的例子,但它们似乎都是成双成对的,不管它们是否有匹配的单词。
所以我要找的是:
File1.txt包含:
Ana=134=address=nonoanneo=othertext Robert=682sd=otherinfo=elseinfo=etc Richard=Carnameother=dog=glasses Paula=Home4562-construction=car Jessica=Koala=6788655=anyothertext=anyothertext
File2.txt包含:
Ana=Yoga 罗伯特=乒乓球 Carlos=Gardening 理查=电子游戏 Jessica=Movies
ExpectedResult.txt
Ana=134=address=nonoanneo=othertext=Yoga 罗伯特=682 etc=otherinfo=otherinfo=etc=Ping pong 理查德=卡纳美其他=狗=眼镜=电子游戏 Jessica=Koala=6788655=anyothertext=anyothertext=Movies
注意,最终结果中没有包含Paula (File1.txt)或Carlos (File2.txt),因为两个文件中都没有匹配的第一个单词。
我在autohotkey中找到了一个可行的解决方案,但是它使用了嵌套循环,每个文件中的大约30.000行代码比较花费了将近半个小时,所以它不是一个选项:/
我知道这个解决方案对你们中的一些人来说可能是轻而易举的,所以提前感谢你们的指点。
发布于 2014-08-30 21:57:20
还有一种使用AutoHotkey (AHK_L)的方法,看看它是否适合您
SetBatchLines, -1
FileRead, file1, .\GeneratedFiles\Text1.ini
FileRead, file2, .\GeneratedFiles\Text2.ini
f2 := []
loop, parse, File2, `n, `r
x:=StrSplit(A_LoopField, "="), f2[x.1] := x.2
loop, parse, File1, `n, `r
if f2[v:=StrSplit(A_LoopField, "=").1]
R .= A_LoopField "=" f2[v] "`r`n"
f2 := []
FileAppend, % Trim(R, "`r`n"), MergeNPCV.ini发布于 2014-08-28 14:49:56
执行标准文件合并的方法是通过公用键对两个文件进行排序,因此任何文件中丢失的记录都可以根据其在文件中的位置立即识别。但是,在这种情况下,没有一个文件是有序的,因此有必要在内存数组中加载整个文件。
下面的批处理文件是这个问题的解决方案,但是批处理文件的速度受到定义的内存变量数量的影响,所以我不能保证它会非常快。我只能希望它比AutoIT解决方案更快.
该方法假设File1.txt中只有一个具有相同密钥的记录。
@echo off
setlocal EnableDelayedExpansion
rem Load the second file in an array
for /F "tokens=1* delims==" %%a in (File2.txt) do set "w[%%a]=%%b"
rem Process the first file, and merge it with the array
(for /F "tokens=1* delims==" %%a in (File1.txt) do (
if defined w[%%a] (
echo %%a=%%b=!w[%%a]!
set "w[%%a]="
)
)) > Result.txt编辑:您可以尝试第二个测试,删除set "w[%%a]="行(和不必要的括号)。这可能会导致更快的执行,这取决于数据。
发布于 2014-08-28 02:48:22
试试这个AutoIT代码:
#include <array.au3>
;The handle of the result file (result.txt)
Local $hResultFile = FileOpen(@ScriptDir&"\result.txt", 1)
;Putting each file into memory
$hfile1 = FileOpen(@ScriptDir&"\file1.txt")
$hfile2 = FileOpen(@ScriptDir&"\file2.txt")
$file1 = FileRead($hFile1)
$file2 = FileRead($hFile2)
;Creating an array with eachline of the files
$aFile1 = StringSplit($File1,@LF)
$aFile2 = StringSplit($File2,@LF)
;looping in the array to test each line
For $i = 1 to UBound($aFile1)-1
;Getting the name to test in File2.txt
$TestName = stringsplit($aFile1[$i],"=")[1]
;Testing if the name exist in File2 and getting the Index in $aFile2 of the finded string
$Index =_ArraySearch($aFile2,$TestName,-1,-1,-1,-1,3)
;If a matching name is found then writing the new line in result.txt
if not @error Then
$Line=StringReplace($aFile1[$i] & "=" & StringSplit($aFile2[$Index],"=")[2],@CR,"")
FileWriteLine($hResultFile,$Line&@CRLF)
EndIf
Next
FileClose($hResultFile)
FileClose($hFile1)
FileClose($hFile2)输出文件为result.txt
https://stackoverflow.com/questions/25539108
复制相似问题