我正在尝试使用 bash 脚本中的 sed 命令在日志文件中获取一定的时间戳(在我的情况下每 15 分钟一次)。
我的问题是,我可以用变量替换命令中的小时数吗?
这是我想要的脚本:
#!/bin/bash
hour=`date +%H` #Current Hours e.g 14:00
sed -n '/$hour:15:00/,/$hour:30:00/p' file.log | nice grep Event
结果将在 14:15:00 到 14:30:00 之间打印日志文件。但是当范围从 45 分钟到 60 分钟(即 14:45 - 15:00)时会出现问题。有什么解决方案吗?
更新
这个问题已经解决了,下面的命令对我有用。
sed -n "/${hour}:15:00/,/${hour}:30:00/p" file.log | nice grep Event
其他参考:使用变量替换 shell 脚本中的字符串
谢谢。
== 案件已结案 ==
好吧,要回答这个问题 - 是的,您将从引号中删除变量,然后它应该使用以下值:
sed -n '/'$hour:15:00/,/'$hour':30:00/p' file.log | nice grep Event
您也可以只在表达式周围使用双引号
sed -n "/${hour}:15:00/,/${hour}:30:00/p" file.log | nice grep Event