如何使用sed从字符串中提取文本? [英] How to extract text from a string using sed?

查看:288
本文介绍了如何使用sed从字符串中提取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例字符串如下:

This is 02G05 a test string 20-Jul-2012

现在我要从上述字符串中提取02G05.为此,我用sed尝试了以下正则表达式

Now from the above string I want to extract 02G05. For that I tried the following regex with sed

$ echo "This is 02G05 a test string 20-Jul-2012" | sed -n '/\d+G\d+/p'

但是上面的命令不会打印任何内容,我相信原因是它无法与我提供给sed的模式相匹配.

But the above command prints nothing and the reason I believe is it is not able to match anything against the pattern I supplied to sed.

所以,我的问题是我在这里做错了什么以及如何纠正它.

So, my question is what am I doing wrong here and how to correct it.

当我使用python尝试上述字符串和模式时,我得到了结果

When I try the above string and pattern with python I get my result

>>> re.findall(r'\d+G\d+',st)
['02G05']
>>>

推荐答案

您的sed可能不支持模式\d.尝试使用[0-9][[:digit:]].

The pattern \d might not be supported by your sed. Try [0-9] or [[:digit:]] instead.

要仅打印实际匹配项(而不是整个匹配行),请使用替换项.

To only print the actual match (not the entire matching line), use a substitution.

sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'

这篇关于如何使用sed从字符串中提取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆