如何使用正则表达式和 shell 从字符串中提取值? [英] How to extract a value from a string using regex and a shell?

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

问题描述

我在 shell 中,我有这个字符串:12 BBQ ,45 rofl, 89 lol

I am in shell and I have this string: 12 BBQ ,45 rofl, 89 lol

使用正则表达式:\d+ (?=rofl),我想要 45 作为结果.

Using the regexp: \d+ (?=rofl), I want 45 as a result.

使用正则表达式从字符串中提取数据是否正确?我所做的最好的事情是在一些在线正则表达式编辑器中突出显示价值.大多数情况下,它会从我的字符串中删除该值.

Is it correct to use regex to extract data from a string? The best I have done is to highlight the value in some of the online regex editor. Most of the time it remove the value from my string.

我正在调查 expr,但我得到的只是语法错误.

I am investigating expr, but all I get is syntax errors.

如何在 shell 脚本中提取 45?

How can I manage to extract 45 in a shell script?

推荐答案

你可以用 GNU grep 的 perl 模式做到这一点:

You can do this with GNU grep's perl mode:

echo "12 BBQ ,45 rofl, 89 lol" | grep -P '\d+ (?=rofl)' -o
echo "12 BBQ ,45 rofl, 89 lol" | grep --perl-regexp '\d+ (?=rofl)' --only-matching

-P--perl-regexp 表示 Perl 风格的正则表达式.-o--only-matching 表示只输出匹配的文本.

-P and --perl-regexp mean Perl-style regular expression. -o and --only-matching mean to output only the matching text.

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

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