如何在 bash 中搜索时排除某些模式

发布于 2025-01-13 02:25:15 字数 245 浏览 1 评论 0原文

假设我

 abc-def1-xxx
 abc-def2-yy-vv
 abc-def3
 abc-def4

想输出 abc-def3abc-def4

如果我使用模式 abc-def* 那么它会输出所有内容。 如果我搜索 abc-def*-* 那么它会输出前两个条目 如何获取最后两个条目?

Let's say I have

 abc-def1-xxx
 abc-def2-yy-vv
 abc-def3
 abc-def4

I want to output abc-def3 and abc-def4

If I use the pattern abc-def* then it outputs everything.
If I search for abc-def*-* then it out puts the first two entries
How do I get the last two entries?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

留蓝 2025-01-20 02:25:15

您可以使模式更加具体,匹配带连字符的小写字符并在末尾匹配 1 个或多个数字

  • ^ 字符串开头
  • [az]\+ 匹配 1+ 个字符 az
  • - 字面匹配
  • [az]\+ 匹配 1+ 个字符 az
  • [0-9]\+ 匹配 1+ 个数字
  • $< /code> 字符串结尾

例如

echo "abc-def1-xxx
abc-def2-yy-vv
abc-def3
abc-def4" | grep '^[a-z]\+-[a-z]\+[0-9]\+

输出

abc-def3
abc-def4

您还可以匹配例如 abc-def ,然后匹配 1 个或多个数字:

^abc-def[0-9]\+$

输出

您还可以匹配例如 abc-def ,然后匹配 1 个或多个数字:

You can make the pattern more specific matching lowercase chars with a hyphen and matching 1 or more digits at the end

  • ^ Start of string
  • [a-z]\+ Match 1+ chars a-z
  • - Match literally
  • [a-z]\+ Match 1+ chars a-z
  • [0-9]\+ Match 1+ digits
  • $ End of string

For example

echo "abc-def1-xxx
abc-def2-yy-vv
abc-def3
abc-def4" | grep '^[a-z]\+-[a-z]\+[0-9]\+

Output

abc-def3
abc-def4

You could also match for example abc-def and then 1 or more digits:

^abc-def[0-9]\+$

Output

You could also match for example abc-def and then 1 or more digits:

污味仙女 2025-01-20 02:25:15

假设数据放入文件 data.txt 中,

abc-def1-xxx
abc-def2-yy-vv
abc-def3
abc-def4

获取最后两行的命令是:

grep -E '*[0-9]

说明:

  • -E,该模式被解释为扩展正则表达式。
  • *:任意字符
  • [0-9]:一位数字
  • $:以 $ 之前的字符结尾。所以这里,它表示字符串必须以数字结尾。

因此,它查看 data.txt 中的行,并输出最后一个字符是数字(从 0 到 9)的行。

data.txt

说明:

  • -E,该模式被解释为扩展正则表达式。
  • *:任意字符
  • [0-9]:一位数字
  • $:以 $ 之前的字符结尾。所以这里,它表示字符串必须以数字结尾。

因此,它查看 data.txt 中的行,并输出最后一个字符是数字(从 0 到 9)的行。

Let's say the data in put in a file, data.txt

abc-def1-xxx
abc-def2-yy-vv
abc-def3
abc-def4

The command to get the last two lines is:

grep -E '*[0-9]

Explanation:

  • -E, the pattern is interpreted as an extended regular expression.
  • *: any character
  • [0-9]: one digit
  • $: ends with the character just before the $. So here, it indicates that the string must end with a digit.

So it looks at the lines in data.txt, and outputs the lines where the last character is a digit, from 0 to 9.

data.txt

Explanation:

  • -E, the pattern is interpreted as an extended regular expression.
  • *: any character
  • [0-9]: one digit
  • $: ends with the character just before the $. So here, it indicates that the string must end with a digit.

So it looks at the lines in data.txt, and outputs the lines where the last character is a digit, from 0 to 9.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文