将 2 个文本文件的内容合并到第三个文本文件中 - 逐行

merge content of 2 text files into a third text file - line by line

我正在 php 编写一个琐事脚本,但我遇到了一个无法解决的问题。

我有两个 txt 文件,一个有问题,另一个有答案。

问题文件如下所示:

"How many arms a person has" =>
"How many legs a person has" =>

答案文件如下所示:

  "2",
  "2",

是否可以将答案文件中的行移动或复制到问题文件中,以便在单个文件中获得类似的内容?

"How many arms a person has" => "2",
"How many legs a person has" => "2",

假设文件 1 的内容是 a.txt,文件 2 的内容是 b.txt,结果预计在 c.txt 中,尝试 windows 批处理文件(比如 merge.bat):

@echo off
setlocal EnableDelayedExpansion

set i=0
for /F "delims=" %%a in (a.txt) do (
    set /A i+=1
    set a[!i!]=%%a
)

set i=0
for /F "delims=" %%a in (b.txt) do (
    set /A i+=1
    set b[!i!]=%%a
)

for /L %%i in (1,1,%i%) do echo !a[%%i]! is from !b[%%i]!>> c.txt
ENDLOCAL

编辑答案以解决多重循环问题。

解释:

setlocal EnableDelayedExpansion 启用延迟环境变量扩展,直到遇到匹配的 endlocal 命令,无论 setlocal 命令之前的设置如何。

这可以翻译:

!a[1]! is from !b[1]! 将每一行的内容填充到数组 ab 中,这些内容是从文件 a.txtb.txt.[= 中填充的18=]

您可以在 php 中制作类似的东西:

<?php

$questions = array();
$answers = array();

$questionFile = fopen("path/to/questions.txt", "r");
$answerFile = fopen("path/to/answers.txt", "r");

while($row = fgets($questionFile)) {
    $questions[] = $row;
}

while($row = fgets($answerFile)) {
    $answers[] = $row;
}

fclose($questionFile);
fclose($answerFile);

if(count($questions) === count($answers)) {
    $mergingFile = fopen("path/to/thirdFile.txt", "w+");

    foreach($questions as $key => $question) {
        fwrite($mergingFile, $question . $answers[$key] . "\r\n");
    }

    fclose($mergingFile);
}

我的 JREPL.BAT utility 任务非常简单 - 一个混合 JScrpit/batch 脚本,对文本执行正则表达式 search/replace。 JREPL.BAT 是纯脚本,可​​以在任何 Windows XP 以后的机器上本地运行。

jrepl "^.*" "[=10=]+' '+stdin.ReadLine()" /j /f questions.txt /o merged.txt <answers.txt

上面的命令从 /F 选项指定的文件和重定向的标准输入中读取输入。 /J 选项将替换字符串视为针对每个匹配项执行的 JScript 代码。

如果问题可能跨越多行,那么您可以明确搜索字符串以获得正确的结果:

jrepl "^.*==>$" "[=11=]+' '+stdin.ReadLine()" /j /f questions.txt /o merged.txt <answers.txt