kostyan_SV kostyan_SV - 2 months ago 9
PHP Question

Merge 2 text files based on first column using php

I have 2 log files with multiple lines like

first:

1|2016-04-13|...
3|2016-03-13|...


second:

2|POST|accept: txt|...
3|POST|accept: txt|...


Expected result:

3|2016-03-13|...|POST|accept: txt|...


So I need to combine all data in a single file based on first column (ID) using PHP scripting.

Note: count of rows can be different. Only intersection needed (order sensitive)

Answer

My solution is:

<?php 
    exec ("awk -F'|' -vOFS='|' '(NR==FNR){a[$1]=$0; next}{if(a[$1]){print $2,a[$1]}}' first.log second.log > result.log");
?>

I used exec php function to execute shell script

awk -F'|' -vOFS='|' '(NR==FNR){a[$1]=$0; next}{if(a[$1]){print $2,a[$1]}}' first.log second.log > result.log

Here -F'|' specifies '|' symbol as delimiter, first.log and second.log is my files to merge.