当我检查进程列表并'grep'出我感兴趣的那些时,grep
它本身也包含在结果中.例如,要列出终端:
$ ps aux | grep terminal
user 2064 0.0 0.6 181452 26460 ? Sl Feb13 5:41 gnome-terminal --working-directory=..
user 2979 0.0 0.0 4192 796 pts/3 S+ 11:07 0:00 grep --color=auto terminal
Run Code Online (Sandbox Code Playgroud)
通常我ps aux | grep something | grep -v grep
用来摆脱最后一个条目......但它不优雅 :)
你有一个更优雅的黑客来解决这个问题(除了将所有命令包装到一个单独的脚本,这也不错)
请考虑以下代码:
String commandf = "ls /etc | grep release";
try {
// Execute the command and wait for it to complete
Process child = Runtime.getRuntime().exec(commandf);
child.waitFor();
// Print the first 16 bytes of its output
InputStream i = child.getInputStream();
byte[] b = new byte[16];
i.read(b, 0, b.length);
System.out.println(new String(b));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出是:
/etc:
adduser.co
Run Code Online (Sandbox Code Playgroud)
当我从shell运行时,它当然按预期工作:
poundifdef@parker:~/rabbit_test$ ls /etc | grep release
lsb-release
Run Code Online (Sandbox Code Playgroud)
互联网告诉我,由于管道行为不是跨平台的事实,在Java工厂生产Java的杰出人才无法保证管道工作.
我怎样才能做到这一点?
我不会做所有使用Java构建,而不是我的解析grep
和sed
,因为如果我想改变的语言,我将被迫在语言,这完全是一个没有去重新写我的解析代码.
在调用shell命令时如何让Java进行管道和重定向?
我已经在Java程序中看到了方法调用中使用的管道字符.
例如:
public class Testing1 {
public int print(int i1, int i2){
return i1 + i2;
}
public static void main(String[] args){
Testing1 t1 = new Testing1();
int t3 = t1.print(4, 3 | 2);
System.out.println(t3);
}
}
Run Code Online (Sandbox Code Playgroud)
当我跑这个时,我就得到了7
.
有人可以解释管道在方法调用中的作用以及如何正确使用它吗?