【问题标题】:Add HTML tags around each unix GREP result在每个 unix GREP 结果周围添加 HTML 标记
【发布时间】:2015-04-09 23:48:34
【问题描述】:

我正在编写一个脚本以从日志文件中获取某些文本并将其发布到 html 文件中。我遇到的问题是我希望 grep 的每个结果都在 <p></p> 标签内。

这是我目前所拥有的:

cat my.log | egrep 'someText|otherText' | sed 's/timestamp//'

【问题讨论】:

    标签: html bash ubuntu grep


    【解决方案1】:

    使用egrepsed

    您目前拥有:

    $ echo 'timestamp otherText' | egrep 'someText|otherText' | sed 's/timestamp//'
     otherText
    

    要在文本周围放置 para-tags,只需在 sed 命令中添加一个替换项:

    $ echo 'timestamp otherText' | egrep 'someText|otherText' | sed 's/timestamp//; s|.*|<p>&</p>|'
    <p> otherText</p>
    

    使用awk

    $ echo 'timestamp otherText' | awk '/someText|otherText/{sub(/timestamp/, ""); print "<p>" $0 "</p>"}'
    <p> otherText</p>
    

    或者,从文件my.log获取输入:

    awk '/someText|otherText/{sub(/timestamp/, ""); print "<p>" $0 "</p>"}' my.log
    

    【讨论】:

      【解决方案2】:

      使用sed 换行:

      cat my.log | egrep 'someText|otherText' | sed -e 's/timestamp//' -e 's/^/<p>/' -e 's#$#</p>#'
      

      您可以使用-e 在每一行上执行多个操作。 ^ 匹配行首,$ 匹配行尾。

      【讨论】:

        【解决方案3】:

        这是一个带有单个 sed 的版本:

        sed -n 's#\(timestamp\)\(.*\)\(someText\|otherText\)\(.*\)#\<p\>\2\3\4\<\\p\>#p' my.log
        

        【讨论】:

          猜你喜欢
          • 2016-01-28
          • 2021-10-05
          • 1970-01-01
          • 1970-01-01
          • 2020-08-06
          • 2010-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多