Scala Shell脚本中命令引号使用问题求助
Hey there! I’ve run into this exact quote-escaping headache with Scala’s sys.process before—let’s break down why your command is failing and how to fix it.
The Root Problem
When you run a command like "sed -i '5a some text' to.file".! in Scala, the sys.process library doesn’t pass the string through a shell by default. Instead, it splits the string into arguments literally. That means sed ends up receiving '5a as the first part of its expression (including the single quote), which is why you get the unknown command: ' error—sed doesn’t recognize the single quote as valid syntax.
Working Solutions
1. Use a Seq for Explicit Arguments (Recommended)
This is the cleanest and most reliable approach. By passing each part of the command as a separate element in a Seq, you avoid all quote-escaping headaches because Scala sends each argument directly to sed without shell interference:
import sys.process._ Seq("sed", "-i", "5a some text", "to.file").!
Here, 5a some text is treated as a single, unquoted argument—exactly what sed expects.
2. Force Shell Interpretation with bash -c
If you need to use shell-specific syntax (like wildcards or variable expansion), you can wrap your command in bash -c to let the shell parse it properly. Just make sure to handle quotes correctly:
// Using triple quotes to avoid escaping import sys.process._ """bash -c 'sed -i "5a some text" to.file'""".! // Or with escaped quotes in a regular string "bash -c 'sed -i \"5a some text\" to.file'".!
This tells Scala to run bash, which then parses your sed command just like it would in a regular terminal.
Why Your Previous Attempts Failed
"""sed -i "5a adding some text to" file.text""".!: This splits into arguments likesed,-i,"5a,adding, etc.—the double quotes become part of the argument, which sed rejects."sed -i \'5a adding some text to\' file.text".!: The escaped single quotes are still treated as literal characters in the argument list, so sed sees'5ainstead of5a.
By using Seq or explicitly invoking the shell, you bypass these parsing issues entirely.
内容的提问来源于stack exchange,提问作者user3467471

