regex - 如何匹配这样的重复模式?

标签 regex linux unix grep

我想匹配模式,789。仅使用一个 sed 命令。(没有与“-e”链接的多个命令)

规则是匹配第三个传真之后的号码。

echo "fax 123 def fax tel 456 fax 789 fax 976" | sed 's/xxxxxxx/'

最佳答案

使用 awkfax 作为分隔符:

$ echo "fax 123 def fax tel 456 fax 789 fax ghi" | awk -F'fax ' '{print $4}'
789

使用sed:

$ echo "fax 123 def fax tel 456 fax 789 fax ghi" | sed 's/.*fax \([0-9]\+\).*/\1/'
789

编辑: sed 是基于行的,所以如何使用 grep 首先分割字段:

$ echo "fax 123 def fax tel 456 fax 789 fax 976" | egrep -o 'fax (tel )?[0-9]+'
fax 123
fax tel 456
fax 789
fax 976

然后使用sed指定哪一行(字段):

 $ ... | sed -n '1s/^[^0-9]*//p'
 123

 $ ... | sed -n '2s/^[^0-9]*//p'
 456

 $ ... | sed -n '3s/^[^0-9]*//p'
 789

关于regex - 如何匹配这样的重复模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14072606/

相关文章:

linux - I/O 绑定(bind)与 CPU 绑定(bind)取决于内核?

javascript - 匹配字符串中没有标题大小写的单词 - 正则表达式

javascript - (... 排除->\([\s\S]+\) ...) 的正则表达式?

php - 具有两个连续(相同或不同)匹配项的正则表达式

linux - 使用 'screen' 从 GVIM 分离

python - 如何在 Python 中重置 TCP 套接字?

unix - 在其他应用程序中使用 ssh key 进行身份验证?

c# - 正则表达式提取引号之间的字符串

c - 如何在 Linux 中立即捕获击键?

c - C 枚举的大型 c2hs 推断大小