脚本中的最终命令(sed命令)不起作用

时间:2016-10-23 18:55:36

标签: shell vim sed

我这里有一个脚本文件,名为editfile.script

#!/bin/bash

sed '{
1i \Game Commence\nAre You Ready???\ 
s/game/Game/g
s/points/Points/g
s/the\sthe/the/g 
/^ *$/d
$a It's time
}' "$1"

编辑名为GameOverview

的文件
This game will begin in 3 minutes.
The objective is to score 10 points.
If you score 10 points, u move to the the next round

Good luck, may the the force b w u

现在当我运行.\editfile.script GameOverview(来自C shell)命令行时,我收到了这个输出:

Game Commence 
Are You Ready???
This Game will begin in 3 minutes.
The objective is to score 10 Points.
If you score 10 points, u move to the next round
Good luck, may the force b w u

正如您所看到的,每个命令都已执行:以外的附加命令$a It's time。为什么会发生这种情况,以及如何解决?而且我认为它与前面的"删除所有空白行"有关。命令/^ *$/d,因为当我摆脱它时,"它的时间"附上:

Game Commence 
Are You Ready???
This Game will begin in 3 minutes.
The objective is to score 10 Points.
If you score 10 points, u move to the next round

Good luck, may the force b w u
It's time

1 个答案:

答案 0 :(得分:1)

问题是您要追加的字符串中的单引号It's time。它结束了你的sed命令的开头单引号。

您可以通过结束第一个引号获得单引号,将单引号放在双引号之间,然后启动另一个单引号字符串:

$a It'"'"'s time

要完全避免这个问题,您可以将sed命令放入单独的文件中,而不是将其包装在shell脚本中:

$ cat sedscr.sed
1i\
Game Commence\nAre You Ready???
s/game/Game/g
s/points/Points/g
s/the\sthe/the/g
/^ *$/d
$a\
It's time

我还将ia命令分成两行,这应该是发布这些命令的最便携方式。

然后你可以这样称呼它:

$ sed -f sedscr.sed GameOverview
Game Commence
Are You Ready???
This Game will begin in 3 minutes.
The objective is to score 10 Points.
If you score 10 Points, u move to the next round
Good luck, may the force b w u
It's time

像这样,你不必特别对待单引号。