[英]grep 2 words at if statements in Bash
I am trying to see if my nohup file contains the words that I am looking for. 我正在尝试查看我的nohup文件是否包含要查找的单词。 If it does, then I need to put that into tmp file.
如果是这样,那么我需要将其放入tmp文件中。
So I am currently using: 所以我目前正在使用:
if grep -q "Started|missing" $DIR3/$dirName/nohup.out
then
grep -E "Started|missing" "$DIR3/$dirName/nohup.out" > tmp
fi
But it never goes into the if statement even if there are words that I am looking for. 但是,即使有我要查找的单词,它也永远不会进入if语句。
How can I fix this? 我怎样才能解决这个问题?
Since basic sed uses BRE
, regex alternation operator is represented by \\|
由于基本sed使用
BRE
,因此正则表达式交替运算符由\\|
表示 . 。
|
matches a literal |
匹配文字
|
symbol. 符号。 And you don't need to touch
|
而且您无需触摸
|
symbol in the grep which uses ERE
. grep中使用
ERE
符号。
if grep -q "Started\|missing" $DIR3/$dirName/nohup.out
You should use egrep
instead of grep
(Avinash Raj has explained that in other words already in his answer). 您应该使用
egrep
而不是grep
(Avinash Raj已在其答案中对此进行了解释)。
I would generally recommend using egrep
as a default for everyday use (even though many expressions only contain the basic regular expression syntax). 我通常建议将
egrep
用作日常使用的默认值(即使许多表达式仅包含基本的正则表达式语法)。 From a practical point the standard grep
is only interesting for performance reasons. 从实际的角度来看,标准
grep
仅出于性能原因才很有趣。
Details about the advantages of grep
vs. egrep
can be found in that superuser question . 有关
grep
与egrep
的优点的详细信息可以在该超级用户问题中找到。
When you only put the grep results into the tmp-file, you do not want to grep the file twice. 当您仅将grep结果放入tmp文件中时,就不想将文件grep两次。
You can not use 你不能使用
egrep "Started|missing" $DIR3/$dirName/nohup.out > tmp
since that would create an empty tmp file when nothing is found. 因为那样一来什么也找不到,所以会创建一个空的tmp文件。 You can remove empty files with
if [ ! -s tmp ]
您可以使用
if [ ! -s tmp ]
if [ ! -s tmp ]
or use another solution: if [ ! -s tmp ]
或使用其他解决方案:
Redirectong the grep results without grepping again can be done with 可以重新重定向grep结果而无需再次grepping
rm -f tmp 2>/dev/null
egrep "Started|missing" $DIR3/$dirName/nohup.out | while read -r strange_line; do
echo "${strange_line}" >> tmp
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.