鉴于我有包含内容的日志文件app.log
:
2018-08-29 07:43:17.123-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound request was sent.
2018-08-29 07:43:17.456-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '28' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound response was received.
2018-08-29 07:44:18.789-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound request was sent.
2018-08-29 07:44:18.779-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '28' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound response was received.
2018-08-29 07:45:19.433-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound request was sent.
2018-08-29 07:45:19.998-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '28' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound response was received.
2018-08-29 07:46:20.658-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound request was sent.
2018-08-29 07:46:20.774-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '28' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound response was received.
我想获取我指定为参数的时间戳范围之间的日志行。
请注意,该日志行不仅仅是以时间戳开头的 1 行。该行之后有附加信息,直到出现具有不同时间戳的下一行。
所以在我们的例子中:
2018-08-29 07:43:17.123-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound request was sent.
是 1 个日志行。
所以,我想执行some command 2018-08-29 07:44:00.000 2018-08-29 07:46:00.000 app.log
将返回的内容
2018-08-29 07:44:18.789-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound request was sent.
2018-08-29 07:44:18.779-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '28' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound response was received.
2018-08-29 07:45:19.433-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound request was sent.
2018-08-29 07:45:19.998-0500 CDT [osb_02] [[ACTIVE] ExecuteThread: '28' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO -
[OSB Tracing] Outbound response was received.
另请注意,参数不一定存在于日志文件中。
答案1
sed '1,/pattern1/d;/pattern2/,$d' app.log
应该能解决问题
如果您希望它作为脚本按照您提到的方式运行,那么 ~/.bashrc 中的函数如下所示:
time_log() {
pattern1=$1
pattern2=$2
file=$3
sed "1,/$pattern1/d;/$pattern2/,$d" "$file"
}
然后你可以运行:
time_log "2018-08-29 07:44:" "2018-08-29 07:46:" app.log
编辑:
删除了不必要的cat
要包含第一行,最简单的方法就是grep
在运行之前包含第一行sed
:
time_log() {
pattern1=$1
pattern2=$2
file=$3
grep "$pattern1" "$file"
sed "1,/$pattern1/d;/$pattern2/,$d" "$file"
}
sed
如果有 sed 大师愿意插话的话,可能有更好的方法来做到这一点。