2016-06-12 50 views
0

使用重定向時使用的ProcessBuilder我想用的ProcessBuilder運行此命令:如何在Linux中

sort -m -u -T /dir -o output <(zcat big-zipped-file1.gz | sort -u) <(zcat big-zipped-file2.gz | sort -u) <(zcat big-zipped-file3.gz | sort -u) 

我曾嘗試以下:

// This doesn't recognise the redirection. 
String[] args = new String[] {"sort", "-m", "-u", "-T", "/dir", "-o", "output", "<(zcat big-zipped-file1.gz | sort -u)", "<(zcat big-zipped-file2.gz | sort -u)", "<(zcat big-zipped-file3.gz | sort -u)"}; 

// This gives: 
// /bin/sh: -c: line 0: syntax error near unexpected token `(' 
String[] args = new String[] {"/bin/sh", "-c", "\"sort -m -u -T /dir -o output <(zcat big-zipped-file1.gz | sort -u) <(zcat big-zipped-file2.gz | sort -u) <(zcat big-zipped-file3.gz | sort -u)\""}; 

我使用args這樣的:processBuilder.command(args);

+0

更新了我的問題。我想將幾個zcat命令的輸出重定向到排序。 –

+0

ProcessBuilder不是一個shell。要麼顯式調用shell,要麼自己執行重定向。 – jtahlborn

+0

這不是重複的。這裏的問題是不同的。我在第二次嘗試時明確調用了shell。 –

回答

0

我終於明白了。正如Roman在他的評論中提到的,sh不理解重定向,所以我不得不使用bash。我也必須同時使用輸入流和錯誤流。

String[] args = new String[] {"/bin/bash", "-c", "sort -m -u -T /dir -o output <(zcat big-zipped-file1.gz | sort -u) <(zcat big-zipped-file2.gz | sort -u) <(zcat big-zipped-file3.gz | sort -u)"}; 

ProcessBuilder builder = new ProcessBuilder(); 
builder.command(args); 
Process process = builder.start(); 
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); 
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); 
while((line = input.readLine()) != null); 
while((line = error.readLine()) != null); 

process.waitFor(); 
+0

您使用了'process.getInputStream()'兩次。第二個應該是錯誤流。 – Roman

+0

謝謝。修復! –