2 Stimmen

Mehrere Arten von Kursen anbieten

Hallo, ich habe die folgende Datei:

$ 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

Ich möchte sie mit awk und dem folgenden Unix-Befehl sortieren. Dieser Befehl sortiert die Tab-Datei zuerst nach Spalte1 und dann nach Spalte2.

$ awk 'NR==1; NR > 1 {print $0 | "sort -t\"\t\" -k1 -k2"}' file.txt

und es funktioniert perfekt.

$ 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

Mein Problem beginnt, wenn ich es mit Php als Bash-Argument aufrufen möchte.

Mein Code funktioniert gut, wenn ich aufrufe

print(shell_exec(/bin/bash -c "ls -l")) 

Jetzt möchte ich dasselbe für den Sortierbefehl tun. Unten ist mein 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); 
*/

Hilfe erwünscht. Danke

1voto

anubhava Punkte 713155

Sie brauchen nicht zu verwenden /bin/bash bei Verwendung der Funktion shell_exec. Der gesamte Code kann wie folgt bereinigt werden ( und es funktioniert einwandfrei ):

<?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
?>

0voto

Niet the Dark Absol Punkte 310257

Suchen Sie nach escapeshellarg y escapeshellcmd ?

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X