Tuesday 4 December 2012

Compare two files using PHP and bash Script :)

Hi Friends,

Need to compare two files and searching for different entries in them. Here is the solution.

Create a new file named cmp.sh and put it in a folder.

#!/bin/bash
uniq temp1 > sort_temp1
sort sort_temp1 > sort1.txt
uniq temp2 > sort_temp2
sort sort_temp2 >> sort1.txt
sort sort1.txt > sort_dup.txt
cat sort_dup.txt | uniq > sort.txt
echo "Elements present in file temp1 not in file temp2"
php index.php 1
echo "Elements present in file temp1 not in file temp2"
php index.php 2

Save it.

Now, we need to create a php file named index.php in same folder.

<?php
$handle = @fopen("sort.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);

//======================================
if($argv[1] == 1)
{
$handle1 = @fopen("sort_temp1", "r");
if ($handle1) {
$test = 1;
while (!feof($handle1)) {
$buffer1 = fgets($handle1, 4096);
if ($buffer==$buffer1)
$test = 0;
}
if ($test == 1)
echo $buffer;
}
fclose($handle1);
}
//=========================================

//=========================================
if($argv[1] == 2)
{
$handle2 = @fopen("sort_temp2", "r");
if ($handle2) {
$test = 1;
while (!feof($handle2)) {
$buffer2 = fgets($handle2, 4096);
if ($buffer==$buffer2)
$test = 0;
}
if ($test == 1)
echo $buffer;
}
fclose($handle2);
}
//========================================

    }
    fclose($handle);
}
?>

Save the file in same folder. Add your both files need to compare, with the name temp1 and temp2.

Run the cmd.sh script and it will give you the desired result.

Hope it helps.

Aksshay Sharma
aksshay@live.in

No comments:

Post a Comment