bash - 如何使用 Bash 在两个时间戳之间的文件中搜索行

标签 bash

<分区>

在 bash 中,我试图读取一个日志文件,并且将只打印在两个特定时间之间具有时间戳的行。时间格式为 hh:mm:ss。例如,我将搜索介于 12:52:33 到 12:59:33 之间的行。

我想使用正则表达式,因为我可以在 grep 函数中使用它。

每个日志行都以 some_nr 2014-05-15 21:58:00,000000 rest_of_line 开头。

我的解决方案为我提供了 1 分钟边距的线条。我删除了 ss 并使用 hh:mm:[0-9]{2} 获取所有行。 $2 的格式为 filename_hh:mm:; 例如:"24249_16:05:;24249_16:05:;24249_16:07:;24249_16:07:;24249_16:08:"

我的代码:

B=$2  

for line in ${B//;/ } ;
do  
    TENT=`echo $line | awk '{split($0,numbers,"_"); print numbers[1]}'`"_logs.txt"
    TIME=`echo $line | awk '{split($0,numbers,"_"); print numbers[2]}'`"[0-9]{2}"

    grep -iE ${TIME} ${TENT} >> ${FILE1}
done

我需要一个 15 秒余量的解决方案,而不是 60 秒。我想以 filename_hh:mm:ss 格式输入并获取 hh:mm:ss +/- 15s 或filename_hh:mm:ss(1)_hh:mm:ss(2) 并在 hh:mm:ss(1) 和 hh:mm:ss(2) 之间取行。有时没有行,因此解决方案应该“识别”有时是否匹配输入的间隔。

日志文件如下所示:

1002143 1002143 2014/15/05 22:09:52.937004 bla 
1002130         2014/15/05 22:09:44.786002 bla bla
1001667         2014/15/05 22:09:44.592009 bl a bla
1001667 1001667 2014/15/05 22:09:44.592009 bl a bla

最佳答案

我相信 sed 是最好的选择:

sed -rne '/<timestamp>/,/<timestamp>/ p' <file>

例如:

tiago@dell:~$ sed -rne '/08:17:38/,/08:24:36/ p' /var/log/syslog 
May 16 08:17:38 dell AptDaemon.Worker: INFO: Processing transaction /org/debian/apt/transaction/08a244f7b8ce4fad9f6b304aca9eae7a
May 16 08:17:50 dell AptDaemon.Worker: INFO: Finished transaction /org/debian/apt/transaction/08a244f7b8ce4fad9f6b304aca9eae7a
May 16 08:18:50 dell AptDaemon.PackageKit: INFO: Initializing PackageKit transaction
May 16 08:18:50 dell AptDaemon.Worker: INFO: Simulating trans: /org/debian/apt/transaction/37c3ef54a6ba4933a561c49b3fac5f6e
May 16 08:18:50 dell AptDaemon.Worker: INFO: Processing transaction /org/debian/apt/transaction/37c3ef54a6ba4933a561c49b3fac5f6e
May 16 08:18:51 dell AptDaemon.PackageKit: INFO: Get updates()
May 16 08:18:52 dell AptDaemon.Worker: INFO: Finished transaction /org/debian/apt/transaction/37c3ef54a6ba4933a561c49b3fac5f6e
May 16 08:24:36 dell AptDaemon: INFO: Quitting due to inactivity

关于bash - 如何使用 Bash 在两个时间戳之间的文件中搜索行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23697958/

相关文章:

linux - 使用 sed 或 awk 将第一行中的一个词替换为第二行中的另一个词

linux - 在notepad++中连续搜索两行

linux - 将 Find 命令的输出附加到 Bash 脚本中的变量

BASH如何在脚本终止时执行命令?

regex - 匹配备份文件 (`*~` )

linux - 如何在 bash 中的某一行之后对文件进行排序?

linux - 如何输出shell脚本的开始和停止日期时间(但不输出其他日志)?

linux - 为什么 "which cp | ls -l "不被视为 "ls -l $(which cp)"?

regex - 如何删除文件中以特定数字开头的行?

linux - 在 BASH 中通过 Char 循环替换 Char