Pipe one shell command into another

Andrew via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 30 07:12:26 PST 2016


Hi,

I'd like to run a shell command which involves piping one thing 
into another and then processes the output line by line, i.e. 
something like "ls -l | sort -k5,5n"

What I've come up so far with is:

import std.process;
import std.stdio;

void main(){
   auto pipesLs = pipeProcess(["ls", "-l"], Redirect.stdout);
   auto pipesSort = pipeProcess(["sort", "-k5,5n"], Redirect.all);

   scope (exit) wait(pipesSort.pid);

   foreach(line; pipesLs.stdout.byLine)
     pipesSort.stdin.writeln(line);

   pipesSort.stdin.close;

   foreach(line; pipesSort.stdout.byLine)
     writeln(line);
}

This seems to work on this simple example, but is there a better 
way to do it, and if not, is this reliable? Also, could someone 
explain to me the necessity of the wait command?

Thanks very much

Andrew


More information about the Digitalmars-d-learn mailing list