Hi I have the following file:
$ cat file.txt
col1 col2 col3
zz2 mm uu
pp3 yy kk
ss2 tt ll
zz3 mm uu
pp23 yy kk
ss3 tt ll
ss3 aa 44
33c 22 99
I want to sort it using awk with the following unix command. This command sorts the tab file first on column1 and then on column2.
$ awk 'NR==1; NR > 1 {print $0 | "sort -t\"\t\" -k1 -k2"}' file.txt
and it works perfect.
$ awk 'NR==1; NR > 1 {print $0 | "sort -t\"\t\" -k1 -k2"}' file.txt
col1 col2 col3
33c 22 99
pp23 yy kk
pp3 yy kk
ss2 tt ll
ss3 aa 44
ss3 tt ll
zz2 mm uu
zz3 mm uu
My problem starts when I want to call it using Php as bash argument.
My code works fine if I call
print(shell_exec(/bin/bash -c "ls -l"))
Now I want to do the same for sorting command. Below is my php code:
$inpfile= 'file.txt';
$outfile= 'fileout.txt';
$bash = '/bin/bash ';
print(shell_exec($bash. " -c \"ls -l\"")); print"<br />";
$command = 'awk \'NR==1; NR > 1 {print $0 | "sort -t\"\t\" -k1 -k2" }\' '.$inpfile . " > " . $outfile;
print("<br>". $command); //awk 'NR==1; NR > 1 {print $0 | "sort -t\"\t\" -k1 -k2" }' file.txt > fileout.txt
shell_exec($bash. " -c \"$command\""); //Gives error because of improper quotes.
/*
$escaped = escapeshellarg($command);
$command1 = $bash. ' -c '.$escaped ;
print("<br>". $command1);
//shell_exec($command1);
*/
Help appreciated. Thanks
You don't need to use /bin/bash
while using shell_exec function. You whole code can be cleaned up like this (and it works fine):
<?php
$inpfile= 'file.txt';
$outfile= 'fileout.txt';
$command = 'awk \'NR==1; NR > 1 {print $0 | "sort -t\"\t\" -k1 -k2" }\' '
. $inpfile . ' > ' . $outfile;
var_dump($command);
shell_exec("$command"); // now works fine without any error
?>