Linux命令 - 查找长度为3或8个字母的单词

问题描述 投票:2回答:2

我有一个包含很多单词的文本文件。我需要找到长度为3个字母或长度为8个字母的单词。我可以用下面的命令分别找到3个和8个字母的单词。如何将结果合并为一个输出?

grep -E '^.{3}$' words | wc -w

grep -E '^.{8}$' words | wc -w
regex grep
2个回答
4
投票

另一种方式是:

grep -E '^(.{3}|.{8})$'

并把其他方式放在一起:

grep -E '^.{3}$|^.{8}$'
grep -E -e '^.{3}$' -e '^.{8}$'

检查一下:Alternation with The Vertical Bar or Pipe Symbol

一个例子:

$ cat file
orange
banana
who
what
we
eat
buzzkill
find

$ grep -E '^(.{3}|.{8})$' file
who
eat
buzzkill

$ grep -E '^.{3}$|^.{8}$' file
who
eat
buzzkill

$ grep -E -e '^.{3}$' -e '^.{8}$' file
who
eat
buzzkill

3
投票

如果您想计算3个字母和8个字母的单词,请使用:

grep -Ewc '.{3}|.{8}' file

如果您想查看3个字母和8个字母的单词,请使用:

grep -Ew '.{3}|.{8}' file

因此,如果您的文件包含:

a
be
sea
deee
goldfish
somethinglong

你会得到:

grep -Ewc '.{3}|.{8}' file
2

要么:

grep -Ew '.{3}|.{8}' file
sea
goldfish
© www.soinside.com 2019 - 2024. All rights reserved.