0

I am new to writing in bash and I just finished this long script but I made the mistake of not adding quotation marks to all the variables beginning with the unary operator $. Adding all the quotation marks by hand is going to take a while. Is there a short cut I can use so all the words in the text file beginning with $ get quotation marks around them? So if a line in the file looks like:

python myProgram.py $car1 $car2 $speed1 $speed2

Then after the shortcut it will appear as

python myProgram.py "$car1" "$car2" "$speed1" "$speed2"

I am writing the script using nano.

4

2 回答 2

3

使用全局搜索并用表达式替换(\$\w+)

  1. 使用 切换到搜索和替换模式C-\
  2. 使用 切换到正则表达式模式Alt-R
  3. 键入表达式(\$\w+)。点击输入。
  4. 输入替换表达式"\1"用引号替换捕获的表达式。点击输入。
  5. 在比赛中,全垒打A
于 2014-07-27T20:07:37.863 回答
0

鉴于您的需要,提供基于该编辑器的解决方案似乎不是强制性的。如果你可以访问 shell,你可以试试这个简单的sed命令:

sed -i.bak -r 's/\$\w+/"&"/g' my-script.sh

这远非完美,但应该在您的特定情况下完成这项工作。如果上面的命令:

  • -i.bak将“就地”执行替换——即修改原始文件,使用.bak扩展名进行备份
  • s/..../..../g是使用模式搜索和替换的常用sed命令。搜索模式介于前两者之间。替换在最后两个之间\/
  • \$\w+模式对应于 a$后跟一个或多个字母 ( \w+)。前面的反斜杠$是必需的,因为该字符通常在搜索模式中具有特殊含义。
  • "&"是替换字符串。在那里,&被搜索模式中找到的字符串替换。从广义上讲,这将引号包围任何匹配搜索模式的字符串。
于 2014-07-27T20:06:55.853 回答