【发布时间】:2015-04-09 23:48:34
【问题描述】:
我正在编写一个脚本以从日志文件中获取某些文本并将其发布到 html 文件中。我遇到的问题是我希望 grep 的每个结果都在 <p></p> 标签内。
这是我目前所拥有的:
cat my.log | egrep 'someText|otherText' | sed 's/timestamp//'
【问题讨论】:
我正在编写一个脚本以从日志文件中获取某些文本并将其发布到 html 文件中。我遇到的问题是我希望 grep 的每个结果都在 <p></p> 标签内。
这是我目前所拥有的:
cat my.log | egrep 'someText|otherText' | sed 's/timestamp//'
【问题讨论】:
egrep 和sed
您目前拥有:
$ 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
【讨论】:
使用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\>\2\3\4\<\\p\>#p' my.log
【讨论】: