【发布时间】:2017-05-05 02:00:20
【问题描述】:
我愿意
egrep "[^e]" text.txt
text.txt 在哪里:
hello
mellow
hello
wack
那么准确地说,输出不应该是wack吗?
但终端(BASH)返回
hello
mellow
hello
wack
出于某种原因?
【问题讨论】:
我愿意
egrep "[^e]" text.txt
text.txt 在哪里:
hello
mellow
hello
wack
那么准确地说,输出不应该是wack吗?
但终端(BASH)返回
hello
mellow
hello
wack
出于某种原因?
【问题讨论】:
如果您想与egrep 进行否定匹配,则需要-v 选项。
~]# egrep -v '[e]' text.txt
wack
~]# egrep '[e]' text.txt
hello
mellow
hello
在您的命令中,^ 内的 [e] 匹配输入文件中除 e 之外的所有内容。例如,如果您的输入文件有一个字符串eeee,那么它将返回除eeee 之外的所有内容
~]# egrep '[^e]' text.txt
hello
mellow
hello
wack
如果您将^ 放在[e] 之外,它不会匹配任何内容,因为text.txt 中的字符串都不是以e 开头的。
【讨论】:
[^e] 会做什么呢?我不明白。如果一个单词包含一个 e,那可以吗?
e 之外的任何内容。如果字符串中除了e 之外还有其他字符,那也没用。
e 的东西怎么办?所以不使用-v 标志?
egrep 这里不需要。要查看匹配的内容,您可以使用--color=auto 选项(如果有)
$ grep --color=auto '[^e]' text.txt
hello
mellow
hello
wack
您会注意到除了e 之外的所有字符都已匹配
使用-v 选项,它将返回所有与给定搜索模式不匹配的行
$ grep -v 'e' text.txt
wack
要修改 OP 的正则表达式而不使用-v,需要匹配整行
$ grep '^[^e]*$' text.txt
wack
$ # or with -x if available
$ grep -x '[^e]*' text.txt
wack
【讨论】:
grep 可以进行着色;并非所有 Unix 变体都有这样的grep。