linux - 如何在 bash 脚本中使用空格来 grep 字符串变量

标签 linux bash grep

<分区>

解决方案:我的日期变量格式错误(天数和星期几颠倒了)。我更改了它,然后使用下面@PesaThe 提出的 if 语句代替我的测试。

原帖:

我正在编写一个 bash 脚本作为我服务器日常维护任务的一部分运行。这个特定的工作是在 input_file 中搜索与昨天和今天的时间戳相匹配的条目。这是我的日期变量。

today=$(date "+%a, %b %d %Y")
yesterday=$(date --date=yesterday "+%a, %b %d %Y")

这里是声明,它们应该是这样的:

declare -- adminLogLoc="/opt/sc/admin/logs/"
declare -- adminLog="/opt/sc/admin/logs/201801.log"
declare -- today="Tue, Jan 02 2018"
declare -- yesterday="Mon, Jan 01 2018"
declare -- report="/maintenance/daily/2018-01-02_2.2.txt"

这里有一些实际的日志条目,比如我需要输出的那些。这些是通过 grep $today $adminLog | 找到的grep 错误

2018 年 1 月 2 日星期二 14:38:50 +0000||error|WARNING|13|用于生成源数据的查询 #2464 处于非事件状态。 2018 年 1 月 2 日星期二 14:38:50 +0000||错误|警告|13|用于生成源数据的查询 #2468 处于非事件状态。 2018 年 1 月 2 日星期二 14:38:50 +0000||错误|警告|13|用于生成源数据的查询 #2470 处于非事件状态。 2018 年 1 月 2 日星期二 14:38:50 +0000||error|WARNING|13|用于生成源数据的查询 #2474 处于非事件状态。

这是我要运行的 if 语句:

# Check for errors yesterday
if [ $(grep $yesterday $adminLog|grep "error") != "" ]; then
    echo "No errors were found for $yesterday." >> $report
else
    $(grep $yesterday $adminLog|grep "error") >> $report
fi
# Check for errors today (at the time the report is made, there
# probably won't be many, if any at all)
if [ $(grep $today $adminLog|grep "error") != "" ]; then
    echo "No errors were found for $today." >> $report
else
    $(grep $today $adminLog|grep "error") >> $report
fi

我已经尝试了几种方法,例如在测试中将双引号括在变量周围,等等。当我在设置变量后在命令行中运行 grep 搜索时,它工作得很好,但是当我在测试括号中运行它时,grep 将每个术语(即星期二、一月......等等)用作单独的参数。我也试过了

grep $yesterday $adminLog 2> /dev/null | grep -q error
if [ $? = "0" ] ; then

运气不好。 我怎样才能让这个测试工作,以便我可以将指定的条目输入到我的日志文件中?谢谢。

最佳答案

能否请您尝试以下脚本,如果这对您有帮助,请告诉我。此代码段将有助于简单地打印昨天和今天的日志,如果您想将它们放入输出文件中,我们也可以相应地调整它。

#!/bin/bash
today=$(date "+%a, %b %d %Y")
yesterday=$(date --date=yesterday "+%a, %b %d %Y")    

todays=$(grep "$today" Input_file)
yesterdays=$(grep "$yesterday" Input_file)

if [[ -n $todays ]]
then
        echo "$todays"
else
        echo "no logs found for todays date."
fi

if [[ -n $yesterdays ]]
then
        echo "$yesterdays"
else
        echo "NO logs found for yesterday's date."
fi

关于linux - 如何在 bash 脚本中使用空格来 grep 字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48062457/

相关文章:

bash - 自守护 bash 脚本

bash - 有时重定向不会在 bash 完成时展开

bash - 带正负过滤的多行 grep

regex - 仅当第二列中的内容为正数时才返回输出的所有列

linux - Windows 或 Linux 用于 FPGA 开发?

linux - 我应该为守护进程使用 C++ 还是脚本?

ruby-on-rails - Ruby on Rails 如何创建用于启动和停止程序的多个按钮

c++ - 使用 Linux 了解 CMake

bash - 使用 sed 将变量打印到文件末尾

regex - 使用 grep 查找动态文本