如果文件存在,下面的脚本可以在文件中找到"bots、spyware、virus“等不同单词的特定数组。
#!/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发布于 2016-10-08 13:42:25
以下是问题部分的解决方案。
当grep在文件KEYWORDS FILE**.**中找到数组的至少一个条目时,转到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[@]}"
数组的每个条目展开为一个引号字符串。在这里"virus" "two words" "special chars .+*?|()[]^&""${KEYWORDS[@]/#/-e}"
将-e准备到数组的每个条目。Grep可以使用此选项搜索多个模式。grep -e"FirstPattern" -e"SecondPattern" ...grep Pattern -- "$FILE"
--是一个提示,说明"$FILE"应该被解释为文件名。它可以命名一个文件-eFunny,这将停止我们的脚本,因为grep会认为没有提供文件名,并将等待输入从stdin。这并不是真正必要的,但一个良好的习惯建立。所谓的双破折号适用于大多数命令,而不仅仅是grep。https://stackoverflow.com/questions/39932548
复制相似问题