[英]Greping exact match/substring
I have a set of words which looks like: 我有一组类似的单词:
fruits.txt fruits.txt
APPLE,2
apple,3
APPLE-ORANGE,3
APPLEORANGE-GRAPE,5
and trying to print "apples" only. 并尝试仅打印“苹果”。
here is what i've tried and almost all the commands with similar problem return the same output as follows: 这是我尝试过的,几乎所有具有类似问题的命令都返回相同的输出,如下所示:
grep -iE "apple\\b" fruits.txt
APPLE,2 APPLE,2
apple,3 苹果,3
APPLE-ORANGE,3 ##this is the extra line which i want to ignore APPLE-ORANGE,3 ##这是我要忽略的多余行
also i've tried the following, but didn't return anything. 我也尝试了以下内容,但未返回任何内容。
grep -i '^apple$' fruits.txt
EXPECTED OUTPUT 预期的输出
APPLE,2 APPLE,2
apples,3 苹果,3
PS: Please don't suggest on grep -iE 'apple\\b' fruits.txt | grep -v "-"
PS:请不要在
grep -iE 'apple\\b' fruits.txt | grep -v "-"
上提出建议grep -iE 'apple\\b' fruits.txt | grep -v "-"
grep -iE 'apple\\b' fruits.txt | grep -v "-"
I can't use this in a loop in case of greping "APPLE-ORANGE", again It'll be a problem. grep -iE 'apple\\b' fruits.txt | grep -v "-"
如果使用“ APPLE-ORANGE”,我不能在循环中使用它,这将再次成为问题。
Try: 尝试:
grep -i 'apple[ ,]' fruits.txt
grep -iP 'apple\b(?=[\s,])' fruits.txt
from the 来自
APPLE,2
apple,3
APPLE-ORANGE,3
APPLEORANGE-GRAPE,5
applE , 8
AAple900
both prints 都印
APPLE,2
apple,3
applE , 8
Both regexes search for case insensitive apple followed by at least one 两个正则表达式都搜索不区分大小写的苹果,然后搜索至少一个
(space) or
,
. (空间)或
,
。
if you don't want accept 如果你不想接受
(space) just remove the character groups...
(空格)只需删除字符组...
Or, you should say to grep
what isn't allowed to follow the apple
, like: 或者,你应该说
grep
什么是不允许追随apple
,如:
grep -iP 'apple[^\w-]' fruits.txt
grep -iE 'apple[^[:alnum:]-]' fruits.txt
search for apple
what isn't followed by any word character or -
. 搜索
apple
后面没有任何单词字符或-
单词 。
You could use awk
for this task: 您可以将
awk
用于此任务:
$ awk -F, -v IGNORECASE=1 '$1 ~ /^apple$/' fruits.txt
APPLE,2
apple,3
If you want to pass awk
a shell variable to be used, you could do this: 如果要向
awk
传递要使用的shell变量,可以执行以下操作:
$ fruit=apple
$ awk -F, -v IGNORECASE=1 -v FRUIT="^$fruit\$" '$1 ~ FRUIT' fruits.txt
APPLE,2
apple,3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.