将终端命令分配给bash变量时出错

时间:2014-08-11 20:49:47

标签: regex bash

我正在尝试制作一个小型shell程序来获取幸运饼干报价。当我在我的终端中运行它(几乎)工作正常

curl -s http://www.fortunecookiemessage.com | grep -oP '(<div class=\"quote\").*(</div>)' | sed 's/.*link\">\(.*\)<\/a>.*/\1/'

但是当我尝试将相同的内容添加到我的bash脚本(run.sh)中时,就像这样

sentence=$(curl -s http://www.fortunecookiemessage.com | grep -oP '(<div class=\"quote\").*(</div>)' | sed 's/.*link\">\(.*\)<\/a>.*/\1/')

它给了我一个错误如下

bash-3.2# sh run.sh 
usage: grep [-abcDEFGHhIiJLlmnOoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
    [-e pattern] [-f file] [--binary-files=value] [--color=when]
    [--context[=num]] [--directories=action] [--label] [--line-buffered]
    [--null] [pattern] [file ...]

我需要帮助来解决这个问题。此外,有时提取的引用格式为<p>QUOTE</p>。这不是所有的时间,但有时只是。我想知道我必须在sed命令中的正则表达式中更改,以便在发生<p></p>标记时删除它。

我的输出设置为-x

bash-3.2# sh run.sh 
++ curl -s http://www.fortunecookiemessage.com
++ grep -oP '(<div class=\"quote\").*(</div>)'
++ sed 's/.*link\">\(.*\)<\/a>.*/\1/'
usage: grep [-abcDEFGHhIiJLlmnOoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
    [-e pattern] [-f file] [--binary-files=value] [--color=when]
    [--context[=num]] [--directories=action] [--label] [--line-buffered]
    [--null] [pattern] [file ...]
(23) Failed writing body
+ sentence=
+ echo

4 个答案:

答案 0 :(得分:2)

您的grep似乎不支持-P选项。将您的grep命令更改为:

grep -Eo '<div class="quote".*</div>'

答案 1 :(得分:1)

您可以使用Perl one liner做到:

perl -Mojo -E 'say g(q(http://www.fortunecookiemessage.com))->dom(q(div[class=quote]))->all_text'

但您需要安装Mojolicious oneliners module套件。

答案 2 :(得分:1)

非常感谢你们。 anubhava的评论帮我解决了这个问题。最后的答案是

sentence=$(curl -s http://www.fortunecookiemessage.com | grep -Eo '(<div class=\"quote\").*(</div>)' | sed 's/.*link\">\(.*\)<\/a>.*/\1/' | sed 's/<[^>]*>//g')

答案 3 :(得分:0)

在交互模式和非交互模式下运行Bash时,您可能设置了不同的环境,并且可能是您在两种情况下都没有启动相同的grep

比较在终端中运行which grep时的输出和添加到脚本时相同命令的输出。如果它们不同,请在终端中运行时使用该命令的输出,以指定脚本中grep的完整路径。

或者,正如@anubhava建议的那样,更改命令参数以摆脱有罪的选项。