Harsh Gupta
Harsh Gupta

Reputation: 331

Running perl command from scala process

I have to make this command run from my scala code

perl -ne '/pattern/ && print $1 and last' filename

I have tried

val re = """pattern"""
 val file = "filename"
 val v= (Process(Seq("""perl -ne '/"""+re+"""/ && print $1 and last' """+file))).!!

But some how despite generating the same command required for command line its still not working.It says:

java.io.IOException: Cannot run program "perl -ne '/pattern/ && print $1 and last' file": error=2, No such file or directory.

Can anyone suggest where its going wrong ?

Upvotes: 2

Views: 536

Answers (1)

Faiz
Faiz

Reputation: 16255

Maybe you need something like this?

 val pattern: String = "..." // your pattern
 val perlCode = s""" '/$pattern/ && print $$1 and last' """
 val v = (Process(Seq("perl", "-ne", perlCode, file))).!!

The issue is Process takes a Sequence of arguments that will be executed. In your case, perl -ne '/pattern/ && print $1 and last' filename

perl is the first, -ne the second, followed by the perl code /pattern/ && print $1 and last (note that the single quotes ' are not relevant, they are just used to ensure that the string of code is passed as a single argument to perl) and last you have the filename.

The scala.sys.process docs show you pretty much everything. If your file is an java.io.File, try:

 val perlCmd = Seq("perl", "-ne", perlCode)
 val file = new java.io.File("/tmp/f.txt")
 val result = perlCmd #< file !!

Which is the same as

perl -ne '/pattern/ && print $1 and last' < /tmp.txt

Upvotes: 2

Related Questions