【问题标题】:Loop to filter out lines from apache log files循环过滤掉apache日志文件中的行
【发布时间】:2019-11-14 13:55:26
【问题描述】:

我有几个 apache 访问文件,我想在分析它们之前先清理一下。我正在尝试通过以下方式使用 grep:

grep -v term_to_grep apache_access_log

我有几个要 grep 的术语,所以我将每个 grep 操作都管道化如下:

grep -v term_to_grep_1 apache_access_log | grep -v term_to_grep_2 | grep -v term_to_grep_3 | grep -v term_to_grep_n > apache_access_log_cleaned

直到这里,我的基本脚本按预期工作!但是我有很多 apache 访问日志,我不想对每个文件都这样做。我已经开始编写一个 bash 脚本,但到目前为止我无法让它工作。这是我的尝试:

for logs in ./access_logs/*;
do
    cat $logs | grep -v term_to_grep | grep -v term_to_grep_2 | grep -v term_to_grep_3 | grep -v term_to_grep_n > $logs_clean
done;

谁能指出我做错了什么?

【问题讨论】:

  • 错误信息是什么?您应该引用您的 $log 变量。您可以使用grep 'foo\|bar'egrep foo|bar 进行交替。
  • 我引用了 '$log',现在我得到: cat: '$log': 没有这样的文件或目录。我的脚本在 /access_logs 文件夹之外
  • 嗯,我的意思是你应该这样引用:"$logs".
  • 引用错误!如果想让 Bash 扩展引号内的变量,则需要使用双引号;单引号禁止任何扩展。
  • 什么不起作用?

标签: linux bash loops grep


【解决方案1】:

如果你有一个变量并且你在它的名字后面附加了_clean,那是一个新变量,而不是附加了_clean 的旧变量的值。要解决这个问题,请使用花括号:

$ var=file.log
$ echo "<$var>"
<file.log>
$ echo "<$var_clean>"
<>
$ echo "<${var}_clean>"
<file.log_clean>

没有它,您的管道会尝试重定向到空字符串,这会导致错误。请注意,"$file"_clean 也可以使用。

至于您的管道,您可以将其组合成一个 grep 命令:

grep -Ev 'term_to_grep|term_to_grep_2|term_to_grep_3|term_to_grep_n' "$logs" > "${logs}_clean"

不需要cat,只需调用一次grep。

或者您可以将所有条款都放入一个文件中:

$ cat excludes
term_to_grep_1
term_to_grep_2
term_to_grep_3
term_to_grep_n

然后使用-f 选项:

grep -vf excludes "$logs" > "${logs}_clean"

如果您的术语是字符串而不是正则表达式,您可以使用-F(“固定字符串”)来加快速度:

grep -vFf excludes "$logs" > "${logs}_clean"

不过,我认为 GNU grep 会自行为您检查。

【讨论】:

  • 非常感谢您的回答!这实际上解决了我的问题,让我学到了新的东西!现在,我为文件夹中的每个 Apache 访问文件获得了一个单独的新重命名文件!
【解决方案2】:

您正在循环多个文件,但在循环中您会不断覆盖结果文件,因此它只会包含最后一个文件的最后一个结果。

你不需要循环,用这个代替:

egrep -v 'term_to_grep|term_to_grep_2|term_to_grep_3' ./access_logs/* > "$logs_clean"

注意,使用 set -eEuCo pipefail 启动 Bash 脚本总是有帮助的。这会捕获最常见的错误——当您尝试破坏 $logs_clean 文件时,它会因错误而停止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多