【问题标题】:Running perl command from scala process从 scala 进程运行 perl 命令
【发布时间】:2013-11-11 12:56:05
【问题描述】:

我必须让这个命令从我的 scala 代码中运行

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

我试过了

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

但有些方法尽管生成了命令行所需的相同命令,但它仍然无法正常工作。它说:

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

谁能指出哪里出了问题?

【问题讨论】:

    标签: regex scala command system


    【解决方案1】:

    也许你需要这样的东西?

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

    问题是Process 需要一个Sequence 将被执行的参数。在你的情况下, perl -ne '/pattern/ && print $1 and last' filename

    perl是第一个,-ne是第二个,后面是perl代码/pattern/ && print $1 and last(注意单引号'是不相关的,它们只是用来保证代码串通过作为perl 的单个参数),最后你有文件名。

    scala.sys.process docs 向您展示了几乎所有内容。如果您的文件是java.io.File,请尝试:

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

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

    【讨论】:

    • 如果我使用文件作为 java.io.File 而不是作为字符串的文件怎么办?那么代码将如何变化?
    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多