【问题标题】:Final command in script (sed commands) not working脚本中的最终命令(sed 命令)不起作用
【发布时间】:2017-03-05 12:52:33
【问题描述】:

我这里有一个脚本文件,叫做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

【问题讨论】:

    标签: shell vim sed


    【解决方案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
    

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

    【讨论】:

    • 不错,但我认为这不是问题所在。我将附加的字符串更改为没有单引号的内容,问题仍然存在。
    • @KevinMoy 奇怪,它适用于我的 sed。 a 命令的正确语法怎么样,比如$a \It's time,甚至是 POSIX 规定的 $a\,然后是换行符,然后是要插入的字符串?
    • 我想我找到了问题所在。在最后一行“祝你好运,愿力量与你同在”的正下方,我发现有一个额外(空白)换行符。一旦我从原件中删除它,问题就立即解决了。您知道为什么由于末尾有多余的换行符而无法显示附加内容吗?
    • Yes :) d 命令使您的脚本前进到下一行,因为没有什么可做的,即,d 命令后面的所有命令都不会执行。跨度>
    • 当我在末尾说额外的换行符时,我指的是原始文本文件(由 sed 脚本编辑)
    猜你喜欢
    • 2013-12-04
    • 1970-01-01
    • 2016-09-06
    • 2014-09-16
    • 2016-09-15
    • 2014-04-18
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多