bash - 在数组中使用 grep

标签 bash shell

下面的脚本用于在文件中查找不同单词“机器人、 spy 软件、病毒”的特定数组(如果文件存在)。

#!/bin/bash

#strings to find in file
NAME[0]="bots"
NAME[1]="spyware"
NAME[2]="virus"

#location of file
LOGS=/home/testing.txt

#define function to grep any of the above mentioned array strings in file
func(){
if `grep "${NAME[*]}" $LOGS`; then
echo "CRITICAL: ${NAME[*]}"
else
echo "errors not found"
exit
fi
}

#file exist or not exist
if [ -f $LOGS ]; then
   echo " File Found"

  #call functions
  func
  modified

  else
   echo "File Not Found"
   exit

但是 grep "${NAME[*]}"$LOGS 不起作用。它显示以下错误:

grep: virus: No such file or directory
grep: bots: No such file or directory

最佳答案

这是问题部分的解决方案。

当 grep 在文件 FILE 中找到数组 KEYWORDS 的至少一项时,转到 if-body。
以下代码适用于具有空格 * 等特殊字符的数组条目。

KEYWORDS[0]="virus"
KEYWORDS[1]="two words"
KEYWORDS[2]="special chars .+*?|()[]^&"

if grep -qF "${KEYWORDS[@]/#/-e}" -- "$FILE"; then
    # found a keyword
fi

这里发生了什么?

  • grep -q
    不要输出任何东西。在第一场比赛时退出。如果我们已经找到关键字,则无需扫描整个文件。

  • grep -F
    搜索固定字符串。 *|+ 等字符失去其特殊含义。

  • “{KEYWORDS[@]}”
    数组的每个条目都会扩展为一个带引号的字符串。这里“病毒”“两个单词”“特殊字符.+*?|()[]^&”

  • “${KEYWORDS[@]/#/-e}”
    -e 添加到数组的每个条目之前。 Grep 可以使用此选项搜索多个模式。 grep -e"FirstPattern"-e"SecondPattern"...

  • grep 模式 -- "$FILE"
    -- 是一个提示,"$FILE" 应被解释为文件名。可以将文件命名为 -eFunny,这会停止我们的脚本,因为 grep 会认为未提供文件名,并会等待来自 stdin 的输入。这里并不是真的有必要,但要养成一个好习惯。所谓的双破折号适用于大多数命令,而不仅仅是 grep。

关于bash - 在数组中使用 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932548/

相关文章:

java - Linux权限运行但不能读取文件

linux - 在 bash 脚本中编码字符串的 URL

bash - 如何将一个文件逐行放入另一个文件中

bash - "' C :\Program ' is not recognized as an internal or external command" error when using Azure CLI

linux - 将内容传递给 EDITOR 并在退出后获取结果(例如 git/svn commit)

bash - 如何过滤掉./gradle project:dependencies命令的特定部分? (版本2)

linux - 如何只列出文件名而不是目录中的属性(在 Linux 中)?

linux - 在多个服务器的 Linux 中搜索多个目录中的字符串

bash - 如何使用 shell 验证 IPv6 地址格式?

linux - 检查文件是否是今天创建的