尝试查看服务帐户登录的次数

尝试查看服务帐户登录的次数

嗨,我是 shell 脚本的新手,我想看看一个账户在日志文件中登录了多少次。如果一个账户登录超过 20 次,我需要打印这些账户的名称。

我正在尝试以下方法

#!/bin/bash
a = 20
cat mongod.log* | grep sa_mg | wc -l
if [sa_mg <= a]
then

答案1

cat mongod.log* | grep sa_mg | wc -l

应该与

grep -c sa_mg mongod.log*

您应该将返回值分配给一个(新)变量,如下所示:

b=$(grep -c sa_mg mongod.log*)

然后,您可以将该值(用检查echo $b)与您的变量进行比较a

完整的脚本如下所示(也纠正了测试):

#!/bin/bash
a = 20
b = $(grep -c sa_mg mongod.log*)
if [ $b -le a ]
then
  echo There are less then $a line matching
fi

答案2

对于新手来说,一种非常常见的被认为是“不正确”的模式是

cat "$filename" |  grep "$some_string"

|因为使用时不需要管道:

grep  "$some_string" "$filename"

稍微更高级和性能更好的是使用 GNU 版本 grep 中的一些开关:

man grep

  -c, --count
          Suppress normal output; instead print a count of matching
          lines for each input file. 

grep "$some_string"这立即和自然地给出了与将输出管道传输到相同的匹配行数| wc -l

当您只想知道某个字符串是否在文件中出现了 20 次或更多次时:您可以在grep找到 20 行匹配的行后停止处理文件内容,这对于可能包含大量出现的 100 GB 或更大的文件的非常有用 "$some_string"

man grep

-m NUM, --max-count=NUM
          Stop reading a file after NUM matching lines.  If NUM is
          zero, grep stops right away without reading input.  A NUM
          of -1 is treated as infinity and grep does not stop; this
          is the default.  If the input is standard input from a
          regular file, and NUM matching lines are output, grep
          ensures that the standard input is positioned to just
          after the last matching line before exiting, regardless of
          the presence of trailing context lines.  This enables a
          calling process to resume a search.  When grep stops after
          NUM matching lines, it outputs any trailing context lines.
          When the -c or --count option is also used, grep does not
          output a count greater than NUM.  

然后就变成了(未经测试和未经提炼)

/bin/bash 

some_string="sa_mg"
filename="mongod.log*"

count=$(grep -c -m 20 "$some_string" "$filename")

if [ "$count" -ge "20" ] ; then 
  echo "found 20 or more occurrences"
fi

使用例如来检查你的 shell 脚本代码https://www.shellcheck.net/(或本地安装的 linter)将帮助您编写“更好”的脚本。

相关内容