regex - grep:如何使用非捕获组?

标签 regex shell grep

我对以下命令感到困惑

$ cat num.txt  
1
2
3
1st
2nd
3th
$ cat num.txt | grep -Eo '[0-9](?:st|nd|th)?'  

我认为它应该输出为

1 
2 
3
1
2
3

但它输出为

1
2
3
1
2nd
3th  

我在这里做错了什么?感谢您的帮助。

最佳答案

您可以使用:

grep -Eo '^[0-9]+' file
1
2
3
1
2
3

或者在grep -P中使用lookahead:

grep -Po '[0-9]+(?=st|nd|th)?' file
1
2
3
1
2
3

关于regex - grep:如何使用非捕获组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314585/

相关文章:

linux - 仅当所有模式在同一订单上匹配时才提取多行

.net - 正则表达式不等于字符串

regex - Vim 语法文件与\zs 不匹配

python - 如何找到匹配项并使用 RegEx 更新它?

linux - 为什么从 .bash_profile 导出的变量而不是别名在非登录 shell 中工作?

linux - grep 字符后面没有字符

javascript - 在 Nodejs 中使用正则表达式停止流程

linux - 从 Windows 添加 Shell 脚本到 CVS

linux - Bash 脚本 : Storing command with spaces and arguments in variable and then executing

unix - 是否有一些 Unix 实用程序可以让我通过很少的输入来 grep 多个文件?