英文:
How do I use grep to find words of specified or unspecified length?
问题
找到所有满足以下条件的单词:
- 至少 n 个字符
- 最多 n 个字符
- 恰好 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:
- At least n characters
- At most n characters
- 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 '\<\w{8}\>' # exactly 8
grep -o -E '\<\w{8,}\>' # 8 or more
grep -o -E '\<\w{,8}\>' # 8 or less
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论