2012-01-31 38 views
2

的,您好我有以下文件:引用多種類型報價

$ 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 

我想用awk與以下UNIX命令來排序。該命令首先在列1上然後在列2上對選項卡文件進行排序。

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

它的工作完美。

$ 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 

當我想用Php作爲bash參數調用它時,我的問題就開始了。如果我叫

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

現在我想做的排序命令相同

我的代碼工作正常。以下是我的php代碼:

$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); 
*/ 

幫助讚賞。 謝謝

+0

你絕對需要一個shell腳本來完成呢?你可以很容易地在PHP中完成這項工作,爲自己節省兩種語言的麻煩。 – Bojangles 2012-01-31 19:20:51

+0

不是,我更喜歡awk,因爲我猜它可能要快得多。我有多個包含大量條目的文件。 – learner 2012-01-31 19:32:10

+0

啊,這很公平。從你給出的例子中,我可以看到PHP是一個更好的選擇,但是,對於大型數據集,「awk」更快。 – Bojangles 2012-01-31 21:31:52

回答

1

使用shell_exec函數時,不需要使用/bin/bash。你整個代碼可以被清理這樣的(和正常工作):

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

在我的系統中,php默認調用sh。不過,我需要bash被調用。這就是爲什麼我使用/ bin/bash。 – learner 2012-01-31 22:21:54

0

您是否在尋找escapeshellargescapeshellcmd

+0

是的,我嘗試了不同的選項,但是由於命令中的「\ t」導致問題,我失敗了。 – learner 2012-01-31 19:33:18