有什么办法可以grep
实现 AND 功能吗?我的意思是这样的:
我有这些行:
I have this one line
I don't have this other line
I have this new line now
I don't have this other new line
This line is new
所以我想grep
找到同时包含“new”和“line”一词的行,而不仅仅是“new line”。我知道我可以这样做:
grep new file | grep line
但这不是我要找的。我希望用一个grep
命令来完成此操作。这是因为该脚本将让用户输入这两个术语,而其中一个术语可能为空,然后会引发错误grep
并中断脚本。
答案1
如果第二项为空或未设置,则不要运行第二项grep
:
grep -e "$term1" <file |
if [ -n "$term2" ]; then
grep -e "$term2"
else
cat
fi
这适用于调用的文件grep
中的模式,然后根据是否非空,对结果应用第二个,或用作直通过滤器。$term1
file
$term2
grep
cat
请注意,这有效地实现了“ term1
AND term2
”,除非当term2
为空时它退化为“ term1
”。
如果您根本不想运行grep
,而是在第二项为空时返回空结果:
if [ -n "$term2" ]; then
grep -e "$term1" <file | grep -e "$term2"
fi
这有效地实现了“ term1
AND term2
”并将空视为 term2
“假”。
这样做的好处是它只依赖于标准grep
,并且两种模式保持独立,这使得它易于理解和维护。
答案2
这将起作用(使用 GNU grep
):
grep -P '(?<=new)\s(?=line)' file
测试:
$ cat > file
I have this one line
I don't have this other line
I have this new line now
I don't have this other new line
This line is new
^D
$ grep -P '(?<=new)\s(?=line)' file
I have this new line now
I don't have this other new line
答案3
尝试将man grep
“串联”与“交替”结合起来:
P1=line
P2=new
grep "$P1.*$P2\|$P2.*$P1" file
I have this new line now
I don't have this other new line
This line is new