Reputation: 23
I want to read a file line by line and search each lines another file with php script on unıx.an write results to another file.
How can I do this? I mean;
file1:
192.168.1.2
192.168.1.3
192.168.1.5
file2:
.....
192.168.1.3
192.168.12.123
192.168.34.56
192.168.1.5
....
file3:
192.168.1.3
192.168.1.5
I want to read file1 each lines and search each line file2.And if I have matches this search write results file3.
Upvotes: 0
Views: 197
Reputation: 436
<?php
$file1 = file('file1', FILE_SKIP_EMPTY_LINES);
$file2 = file('file2', FILE_SKIP_EMPTY_LINES);
$file3Content = implode('', array_intersect($file1, $file2));
file_put_contents('file3', $file3Content);
Upvotes: 1
Reputation: 7948
In PHP you could read both files using file()
function and they will both return as an array. Then use array_intersect()
. Consider this example:
$ip1 = file('ip1.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$ip2 = file('ip2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$results = array_intersect($ip1, $ip2); // intersection of two arrays
$ip3 = implode("\n", $results); // put them back together
file_put_contents('ip3.txt', $ip3); // put it inside the third file
$results
should contain (based on your example) this:
Array
(
[1] => 192.168.1.3
[2] => 192.168.1.5
)
Upvotes: 1