如何循环两个文件并合并相同的文件?
问题描述:
我有两个文本文件,并通过这两个文件要环路,则结合了线(第一测试文件和第二个文本文件的第1行的1号线,这样对千行),并做一些功能如何循环两个文件并合并相同的文件?
我熟悉通过一个文件和代码回路如下:
$lines = file('data.txt');
foreach ($lines as $line) {
//some function
}
但如何将两个文件执行,并结合博特线?
答
不知道你通过表搜索是什么意思到任何分隔符来调整的fread读取的字节数,但打开这两个文件,做的东西与他们:
$file1 = fopen("/path/to/file1.txt","r"); //Open file with read only access
$file2 = fopen("/path/to/file2.txt","r");
$combined = fopen("/path/to/combined.txt","w"); //in case you want to write the combined lines to a new file
while(!feof($file1) && !feof($file2))
{
$line1 = trim(fgets($file1)); //Grab a line of the first file, note the trim will clip off the carriage return/new line at the end of the line, can remove it if you don't need it.
$line2 = trim(fgets($file2)); //Grab a line of the second file
$combline = $line1 . $line2;
fwrite($combined,$combline . "\r\n"); //Write to new combined file, and add a new carriage return/newline at the end of the combined line to replace the one trimmed off.
//You can do whatever with data from $line1, $line2, or the combined $combline after getting them.
}
注意:您可能会遇到麻烦,如果你打一个文件,文件结束前对方,如果他们是不一样的长度,因为这只会发生,可能需要一些if语句来将$ line1或$ line2设置为""
或别的东西,如果feof()
其各自的文件,一旦两个命中文件的结尾,while循环将结束。
答
例子:
$file1 = fopen("file1.txt", "rb");
$file2 = fopen("file2.txt", "rb");
while (!feof($file1)) {
$combined = fread($file1, 8192) . " " . fread($file2, 8192);
// now insert $combined into db
}
fclose($file1);
fclose($file2);
- 你将要使用的两个文件中较长的,而条件。
- 你可能需要根据你的线条有多长
- 变“”你想
答
您可以按照蜡笔和蒂姆所示的方式编程。如果两个文件具有相同的行数,它应该工作。如果行号不同,您将不得不遍历较大的文件以确保您获得所有行或检查EOF。
要逐行组合,我经常使用非常快的unix命令粘贴。这也解释了不同长度的文件。在命令行中运行以下命令:
paste file1 file2 > output.txt
见manpage
为paste
的命令行选项,字段分隔符。
man paste
你是什么意思的“搜索表”?您想要寻找什么? – 2011-02-06 18:45:54
表示将两个文件中的某些数据逐行结合在一起,然后搜索table1并将结果存储到table2。 – limo 2011-02-06 18:49:35