gpt4 book ai didi

regex - GREP 单个整数而不是整个相似的数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:46 24 4
gpt4 key购买 nike

我需要正则表达式方面的帮助来 grep 单个整数。

假设我在一个文本文件中有这些行。

dm-7    14f504e46494c455267494e5a4e642d516a31562d644f394c
dm-70 14f504e46494c455267494e5a4e642d516a31562d644f395c
dm-71 14f504e46494c455267494e5a4e642d516a31562d644f394d
dm-72 14f504e46494c455267494e5a4e642d516a31562d644f394e

我只想 grep“dm-7”而不打印 dm-70、dm-71、dm-72 和 UUID。我怎样才能做到这一点?

grep "^dm-7$"

不会返回任何东西。

谢谢。

最佳答案

使用-w来匹配精确的单词:

$ grep -w 'dm-7' file
dm-7 14f504e46494c455267494e5a4e642d516a31562d644f394c

如果您想确保它以单词 dm- 开头 (^),您也可以使用 grep -w '^dm-7' file 7

来自 man grep:

-w, --word-regexp

Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore.

或者用 awk 也可以:

$ awk '$1=="dm-7"' file
dm-7 14f504e46494c455267494e5a4e642d516a31562d644f394c

甚至使用 sed:

$ sed -n '/^dm-7\s/p' file
dm-7 14f504e46494c455267494e5a4e642d516a31562d644f394c

关于regex - GREP 单个整数而不是整个相似的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com