【问题标题】:How to use Posix Extended Regular Expressions in the shebang of sed interpreter script?如何在 sed 解释器脚本的 shebang 中使用 Posix 扩展正则表达式?
【发布时间】:2011-06-02 01:10:59
【问题描述】:

我写了一个 sed 解释器脚本:

#!/usr/bin/sed -E -f
s/ +/_/g
s/[.':]//g
s/&/and/g

但是,当我运行它时:

$ echo "Bob Dylan" | shscrub.sed
sed: unknown option --  
usage: sed [-aEnru] command [file ...]
       sed [-aEnru] [-e command] [-f command_file] [file ...]

我需要 -E 选项,因为我使用的是扩展正则表达式语法“+”。

任何想法我做错了什么?

编辑

解决方法:

#!/usr/bin/sed -f
s/ \{1,\}/_/g
s/[.':]//g
s/&/and/g

但是,我仍然想知道如何在 shebang (#!) 行中传递两个参数。

【问题讨论】:

  • 你使用的是什么版本的 sed?
  • OpenBSD 4.8 上的默认 sed。说:sed 实用程序符合 IEEE Std 1003.1-2008 (``POSIX'') 规范。标志 [-aEru] 是该规范的扩展。

标签: regex shell sed


【解决方案1】:

错误消息是说空格字符不是一个选项。所以我想,你需要在 shebang 中将所有参数混合在一起:

#!/usr/bin/sed -Ef
s/ +/_/g
s/[.':]//g
s/&/and/g

奇怪,因为这很好用:

$ echo "Bob  Dylan" | sed -E -f ~/bin/shscrub.sed
Bob_Dylan

【讨论】:

  • 在我看来像一个 Gnu sed 错误。
  • +1 Shebang 行通常只能在解释器名称后有一个空格。这就是为什么你必须一起运行参数,即使你可以在命令行上将它们分开。
  • Shebang 行没有环境:$IFS 未设置,因此 shell 不知道使用哪些字符来分隔选项。您可能可以通过转移环境来解决这个问题,也许使用/usr/bin/env
【解决方案2】:

问题是 shebang #! 多个 CLI 参数被 Linux 内核通过 binfmt_misc 视为单个“-E -f”参数:https://stackoverflow.com/a/1667855/895245

正如How to use multiple arguments with a shebang (i.e. #!)? 中提到的,除了使用包装器之外,似乎没有什么好的方法可以解决这个问题。

既然你提到了 POSIX,还要注意这里没有提到 POSIX 7 中的-Ehttp://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html

【讨论】:

    【解决方案3】:

    适用于 OSX 10.6 上的默认 sed;

    [~]> echo "Bob Dylan"|./test.sed
    Bob_Dylan
    

    使用普通的sh 也可以;

    [~]> sh -c "echo \"Bob Dylan\" | ./test.sed" 
    Bob_Dylan
    

    更新:确实不适用于 Gnu sed,似乎是兼容性问题。

    使用GNU sed,如果你不使用-f参数,它就可以工作,注意你必须使用-r而不是-E

    [~]> echo "Bob Dylan"|sed -r "s/ +/_/g;s/[.':]//g;s/&/and/g" 
    Bob_Dylan
    

    【讨论】:

    • 你可以试试:sh -c "echo \"Bob Dylan\" | ./test.sed"
    • 对于 GNU sed,用 -r 代替 -E
    猜你喜欢
    • 2012-03-06
    • 2016-11-11
    • 1970-01-01
    • 2010-09-18
    • 2011-07-04
    • 2017-10-17
    • 2018-03-16
    • 2013-06-12
    • 2012-10-19
    相关资源
    最近更新 更多