Harsh Gupta
Harsh Gupta

Reputation: 331

Using scala variable in executing awk system command in scala

I have a command cat filename | awk 'match($0,/regext_patt/,a) {print a[1] ;exit;}' I want to run this command using scala sys.process. Here "filename" and "regex_patt" will be coming from scala defined variables.So far I am able to manage this :

val extract = (s"cat $file" #| Process(Seq("awk", "match($0,/.+Country=([^;]*);.+/,a) {print a[1] ;exit(0);}"))).!!

Issue here is with the regular expression pattern , which is hard-coded and I am not able to get around with how to use scala variable inside the Seq process builder.

I tried this but its giving errors :

val reg:String = ".+Country=([^;]*);.+"
val extract= (s"cat $file" #| Process(Seq("awk", "match($0,/",reg,"/,a) {print a[1] ;exit(0);}"))).!

and the error here is :

awk: match($0,/
awk:           ^ unexpected newline or end of string
awk: cmd. line:1: match($0,/
awk: cmd. line:1:           ^ unexpected newline or end of string

please help with what key thing I am missing here to sort this out . thanks in advance

Upvotes: 1

Views: 1298

Answers (1)

red1ynx
red1ynx

Reputation: 3775

You can use simple string concatenation: "match($0,/" + reg + "/,a) {print a[1] ;exit(0);}"

Upvotes: 1

Related Questions