在每个 unix GREP 结果周围添加 HTML 标签

Add HTML tags around each unix GREP result

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

这是我目前的情况:

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

使用 egrepsed

您目前拥有:

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

要在文本周围放置副标签,只需向 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>" [=12=] "</p>"}'
<p> otherText</p>

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

awk '/someText|otherText/{sub(/timestamp/, ""); print "<p>" [=13=] "</p>"}' my.log

使用sed换行:

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

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

这是一个只有一个 sed 的版本:

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