Michael Gorham
Michael Gorham

Reputation: 1284

Process and ProcessBuilder

I'm trying to run a process that greps free memory, but the process builder fails to parse the awk portion ...

scala> import scala.sys.process._

scala> "grep MemFree /proc/meminfo" #| "awk '{print $2}'" !
awk: cmd. line:1: '{print
awk: cmd. line:1: ^ invalid char ''' in expression
res16: Int = 1

Same results with this ...

scala> Seq("grep", "MemFree /proc/meminfo") #| Seq("awk", "'", "{print $2}", "'") !
awk: cmd. line:1: '
awk: cmd. line:1: ^ invalid char ''' in expression

Escaping doesn't work either ...

scala> Seq("grep", "MemFree /proc/meminfo") #| Seq("awk", "\"'{print $2}'\"") ! 
res21: Int = 0

How can I get awk '{print $2}' to work? Is there a way to examine what the process builder is trying to execute?

Upvotes: 0

Views: 209

Answers (2)

0__
0__

Reputation: 67290

The apostrophes are only used by the bash to know where the boundaries of arguments are. In Scala, when you use a Seq, these boundaries are given and the apostrophe has no meaning, they are passed to awk which then complains.

import scala.sys.process._

(Seq("grep", "MemFree", "/proc/meminfo") #| Seq("awk", "{print $2}")).!

Also note that the arguments for grep must be separated.


By the way, if you want to get the value into Scala, you can use !!:

(Seq("grep","MemFree","/proc/meminfo") #| Seq("awk","{print $2}")).!!.trim.toInt

Upvotes: 2

Rex Kerr
Rex Kerr

Reputation: 167891

The pair of ' is used in Bash or similar shells to indicate that spaces within are not delimiters for separate arguments. That is '{print $2}' means that the first argument to the awk command should be the string {print $2}.

So you're looking for Seq("awk", "{print $2}").

Upvotes: 0

Related Questions