使用 grep 如何查找指定长度或未指定长度的单词?

huangapple go评论48阅读模式
英文:

How do I use grep to find words of specified or unspecified length?

问题

找到所有满足以下条件的单词:

  1. 至少 n 个字符
  2. 最多 n 个字符
  3. 恰好 n 个字符

对于第一点,您已经找到了解决方案,但是对于第二和第三点可能需要做些更改。尝试以下命令:

  • 最多 n 个字符:grep -E '^.{1,8}$' /sample/dir(在这个例子中,最多是 8 个字符)
  • 恰好 n 个字符:grep -E '^.{8}$' /sample/dir

如果要在 /sample/dir 中只看到特定信息,您可以使用以下命令:

cut -f1 -d: /sample/dir | grep -E '^.{8}$'

这将只显示每行开头的用户名,且用户名恰好是 8 个字符。

对于您想要的三种输出,这些命令可以修改参数以符合条件。同时,应用 cut 命令可以帮助您筛选所需信息。

希望这能帮到您,如有疑问,请随时问我。

英文:

In the Unix command line (CentOS7) I have to use the grep command to find all words with:

  1. At least n characters
  2. At most n characters
  3. Exactly n characters

I have searched the posts here for answers and came up with grep -E '^.{8}' /sample/dir but this only gets me the words with at least 8 characters.

Using the $ at the end returns nothing. For example:
grep -E '^.{8}$' /sample/dir

I would also like to trim the info in /sample/dir so that I only see the specific information. I tried using a pipe:

cut -f1,7 -d: | grep -E '^.{8}' /sample/dir

Depending on the order, this only gets me one or the other, not both.

I only want the usernames at the beginning of each line, not all words in each line for the entire file.

For example, if I want to find userids on my system, these should be the results:

tano-ahsoka
skywalker-a
kenobi-obiwan

2.

ahsoka-t
luke-s
leia-s
ahsoka-t
kenobi-o
grievous

I'm looking for two responses here as I have already figured out number 1.

Numbers 2 and 3 are not working for some reason.

If possible, I'd also like to apply the cut for all three outputs.

Any and all help is appreciated, thank you!

答案1

得分: 0

你可以运行一个grep命令来提取单词,另一个用于基于长度进行过滤。

grep -oE '(\w|-)+' file | grep -Ee '^.{8,}$'
grep -oE '(\w|-)+' file | grep -Ee '^.{,8}$'
grep -oE '(\w|-)+' file | grep -Ee '^.{8}$'

根据要求更新模式,也许可以使用-r并指定一个目录而不是文件。可能还需要添加-h选项以防止打印文件名。

英文:

You can run one grep for extracting the words, and another for filtering based on length.

grep -oE '(\w|-)+' file | grep -Ee '^.{8,}$'
grep -oE '(\w|-)+' file | grep -Ee '^.{,8}$'
grep -oE '(\w|-)+' file | grep -Ee '^.{8}$'

Update the pattern based on requirements and maybe use -r and specify a directory instead of a file. Adding -h option may also be needed to prevent the filenames from being printed.

答案2

得分: 0

根据您对grep的实现,以下方法可能有效:

    grep -o -E '\<\w{8}\>'     # 确切匹配8个字符
    grep -o -E '\<\w{8,}\>'    # 8个或更多字符
    grep -o -E '\<\w{,8}\>'    # 8个或更少字符
英文:

Depending on your implementation of grep, it might work to use:

grep -o -E &#39;\&lt;\w{8}\&gt;&#39;     # exactly 8
grep -o -E &#39;\&lt;\w{8,}\&gt;&#39;    # 8 or more
grep -o -E &#39;\&lt;\w{,8}\&gt;&#39;    # 8 or less

huangapple
  • 本文由 发表于 2023年2月7日 04:29:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定