我试图提取下面给出的数字,但屏幕上没有任何内容:
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)
这是因为您的第一个.*
是贪婪的,并且[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)
方法相匹配的数字,后跟字苹果。
归档时间: |
|
查看次数: |
23424 次 |
最近记录: |