我想匹配模式,789。仅使用一个 sed 命令。(没有与“-e”链接的多个命令)
规则是匹配第三个传真之后的号码。
echo "fax 123 def fax tel 456 fax 789 fax 976" | sed 's/xxxxxxx/'
最佳答案
使用 awk
和 fax
作为分隔符:
$ 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/