sed提取数字组

cho*_*hoc 15 linux sed

我试图提取下面给出的数字,但屏幕上没有任何内容:

echo "This is an example: 65 apples" | sed -n  's/.*\([0-9]*\) apples/\1/p'
Run Code Online (Sandbox Code Playgroud)

但是,如果两个数字分别匹配,我得到'65',如下所示:

echo "This is an example: 65 apples" | sed -n  's/.*\([0-9][0-9]\) apples/\1/p'
65
Run Code Online (Sandbox Code Playgroud)

如何匹配一个数字,以至于我不知道要提取的数字中的位数,例如它可以是2344而不是65?

cod*_*ict 19

$ echo "This is an example: 65 apples" | sed -r  's/^[^0-9]*([0-9]+).*/\1/'
65
Run Code Online (Sandbox Code Playgroud)

  • +1,但要注意并非所有sed支持-r因此不能使用'+'修饰符并且必须逃避parens. (4认同)
  • 为什么像[[([0-9]*)apple]`(http://sprunge.us/feGV)这样的正则表达式在sed中不起作用?它在python中运行得很好. (3认同)

mat*_*fee 6

这是因为您的第一个.*贪婪的,并且[0-9]*允许0或多个数字。因此,.*吞噬最大程度地增加了(包括数字),并且[0-9]*没有匹配项。

你可以做:

echo "This is an example: 65 apples" | sed -n  's/.*\b\([0-9]\+\) apples/\1/p'
Run Code Online (Sandbox Code Playgroud)

在这里,我强制[0-9]匹配至少一位数字,并在数字之前添加了单词边界,以便整个数字都匹配。

但是,使用grep,您只需匹配数字就更容易了:

echo "This is an example: 65 apples" | grep -P -o '[0-9]+(?= +apples)'
Run Code Online (Sandbox Code Playgroud)

-P意思是“Perl的正则表达式”(所以我没有约逃避“+”的担心)。

-o意思是“只打印匹配”。

(?= +apples)方法相匹配的数字,后跟字苹果。