【问题标题】:sed and Applescript shell script - strip character stringsed 和 Applescript shell 脚本 - 去除字符串
【发布时间】:2010-11-22 06:18:29
【问题描述】:

我正在尝试在 Applescript 的 shell 脚本中使用 sed 从变量 the_html 中的这个 html 链接中剥离这个字符串 - ?print=1 - <a href="http://myurl.com.html?print=1">my link</a>

但这会引发错误:

set new_html to do shell script "echo " & quoted form of the_html & " | sed s=?print=1= =g'"

我需要转义“=”吗?

编辑:

现在工作。 Applescript 不喜欢用 \ 转义的 =,但转义整个字符串是可行的:

sed 's/?print=1//g'

【问题讨论】:

    标签: sed applescript


    【解决方案1】:

    试试这个:

    echo '<a href="http://myurl.com.html?print=1">my link</a>' | sed 's/?print=1/ /g'
    

    评论:

    • 将 HTML 放在引号中或对其属性进行转义
    • 使用sed时,一般使用斜线:'s/a/b/'

    【讨论】:

      【解决方案2】:

      这适用于我的 Mac:

      echo '<a href="http://myurl.com.html?print=1">my link</a>' | sed 's=?print\=1= =g'
      

      所以答案是,是的,您确实需要转义 =,因为它使用了表达式分隔符。

      【讨论】:

      • 谢谢,但我忽略了我在 Applescript 中使用 shell 脚本,Applescript 不喜欢 \ 来转义 =。
      【解决方案3】:

      是的。您需要转义具有特殊含义的字符。现在有标准的正则表达式特殊字符,以及您用作分隔符的字符。因此,如果您使用 = 作为分隔符,则需要使用 \ 对其进行转义。

      通常 / 用作分隔符。例外情况是您可能正在搜索 /,这会产生一些非常疯狂且难以阅读的带有所有转义的表达式。因此,如果您要搜索 /s,我建议您使用不同的字符,否则请使用 /。

      要回答最直接的问题,您可以转义 =:

      sed '=print\=1= =g'

      或使用标准斜线,不转义 =:

      sed '/print=1/ /g'

      【讨论】:

        【解决方案4】:

        如果使用另一个 sed 分隔符,例如 '/'',',则无需转义 '='。但是如果你想获取 URL 参数

        带有'?'前缀:

         echo '<a href="http://myurl.com.html?print=1">my link</a>' \
            | sed -e 's,.*\(?.*\)\".*,\1,'
        

        没有'?'

        echo '<a href="http://myurl.com.html?print=1">my link</a>' \
            | sed -e 's,.*?\(.*\)\".*,\1,'
        

        最好的也是拆分参数:

        $ echo '<a href="http://myurl.com.html?print=1&convert=4">my link</a>' \
            | sed -e 's,.*?\(.*\)\".*,\1,' -e 's,&,\n,g'
        print=1
        convert=4
        

        玩得开心! :)

        【讨论】:

          猜你喜欢
          • 2020-06-25
          • 2017-11-17
          • 2015-06-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-20
          • 1970-01-01
          • 2012-12-21
          • 2010-12-12
          相关资源
          最近更新 更多