我想结合grep 的-o
和-v
标志。但我没有得到任何输出。我有文件:
foo
bar
foobar
我打电话:grep -vo foo ./file
我期望什么:
bar
bar
或者
bar
bar
但我没有得到任何输出。
从 grep 的手册页中:
-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
...
-v, --invert-match
Invert the sense of matching, to select non-matching lines.
当我只使用一个标志时,行为正如我所期望的那样。但是如何让 grep 与两个标志同时工作呢?我在 Debian AMD64 上使用 grep (GNU grep) 3.3。
答案1
你要说的grep
是:
- 仅打印
foo
包含它的每一行,并且- Print lines that don't have a
foo
What you meant to tell grep was:
- Print lines that don't match
foo
, or the parts of lines that don't include afoo
That can be reduced to:
- Print every line, but remove
foo
from them
I think sed
is the perfect tool to do this:
$ sed 's/foo//g' ./file
bar
bar
This says: for each line, substitute foo
with nothing globally. By globally it means every instance in the line.
If you also want to delete empty lines:
$ sed -e 's/foo//g' -e '/^$/d' ./file
bar
bar
This says:
- substitute
foo
with nothing globally, then - for each empty line, delete it