bash IF 语句中的 grep
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3943854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grep in IF statement
提问by ErAB
The following script portion read each line in $next
. But when I try to grep particular pattern i.e. "MO"
in $next
, the error is shown on standard output as:
以下脚本部分读取$next
. 但是当我尝试 grep 特定模式 ie "MO"
in 时$next
,错误在标准输出中显示为:
grep: 40922|OPR: No such file or directory
grep: MO: No such file or directory
grep: 12345|OPR: No such file or directory
grep: MO: No such file or directory
grep: 12345|12345|202|local|LMNO: No such file or directory
cat /home/scripts/$E1.out | while read next
do
i=`echo $next | awk -F"|" '{print()}'`
j=`echo $next | awk -F"|" '{print()}'`
k=`echo $next | awk -F"|" '{print()}'`
l=`echo $next | awk -F"|" '{print()}'`
m=`echo $next | awk -F"|" '{print()}'`
n=`echo $next | awk -F"|" '{print()}'`
o=`echo $next | awk -F"|" '{print()}'`
if grep -q "MO" $next
then echo "FOUND;" >> /home/scripts/sql.$E1.out
else echo "NOT FOUND;" >> /home/scripts/sql.$E1.out
fi
done
$E1.out
files looks like :
$E1.out
文件看起来像:
40922|OPR MO 12345|OPR MO 12345|12345|202|local|LMNO
回答by Brian Campbell
The argument you pass in to grep
, $next
, is being treated as a list of filenames to search through. If you would like to search within that line for a string, say, MO
, then you need to either put it in a file and pass that file in as an argument, or pipe it in via standard input.
您传递给grep
,的参数$next
被视为要搜索的文件名列表。如果您想在该行中搜索字符串,例如,,MO
那么您需要将其放入一个文件中并将该文件作为参数传入,或者通过标准输入将其输入。
Here's an example that you can try out on the command line; of course, substitute the variable that you're using for the literal value that I included to illustrate:
这是您可以在命令行上试用的示例;当然,将您使用的变量替换为我用于说明的文字值:
if echo "40922|OPR MO 12345|OPR MO 12345|12345|202|local|LMNO" | grep -q "MO"
then echo "FOUND"
else echo "NOT FOUND"
fi
回答by ghostdog74
if grep -q "MO" ${E1}.out then
echo "found"
else
echo "not found"
fi
回答by Sreesankar
if tmux ls | grep -q "ABC"; then echo "1"; else echo "2"; fi