如何仅使用 sed 输出捕获的组? [英] How can I output only captured groups with sed?

查看:37
本文介绍了如何仅使用 sed 输出捕获的组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉 sed 只输出捕获的组?

Is there a way to tell sed to output only captured groups?

例如,给定输入:

This is a sample 123 text and some 987 numbers

和模式:

/([\d]+)/

我能否以反向引用格式化的方式只得到 123 和 987 输出?

Could I get only 123 and 987 output in the way formatted by back references?

推荐答案

让这个工作的关键是告诉 sed 排除你不想输出的内容以及指定你想要什么.

The key to getting this to work is to tell sed to exclude what you don't want to be output as well as specifying what you do want.

string='This is a sample 123 text and some 987 numbers'
echo "$string" | sed -rn 's/[^[:digit:]]*([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)[^[:digit:]]*/\1 \2/p'

这说:

  • 不要默认打印每一行 (-n)
  • 排除零个或多个非数字
  • 包括一位或多位数字
  • 排除一位或多位非数字
  • 包括一位或多位数字
  • 排除零个或多个非数字
  • 打印替换(p)

通常,在 sed 中,您使用括号捕获组并使用反向引用输出您捕获的内容:

In general, in sed you capture groups using parentheses and output what you capture using a back reference:

echo "foobarbaz" | sed 's/^foo\(.*\)baz$/\1/'

将输出bar".如果您使用 -r(-E for OS X)作为扩展正则表达式,则不需要转义括号:

will output "bar". If you use -r (-E for OS X) for extended regex, you don't need to escape the parentheses:

echo "foobarbaz" | sed -r 's/^foo(.*)baz$/\1/'

最多可以有 9 个捕获组及其反向引用.反向引用按组出现的顺序编号,但它们可以按任何顺序使用并且可以重复:

There can be up to 9 capture groups and their back references. The back references are numbered in the order the groups appear, but they can be used in any order and can be repeated:

echo "foobarbaz" | sed -r 's/^foo(.*)b(.)z$/\2 \1 \2/'

输出a bar a".

outputs "a bar a".

如果你有 GNU grep(它也可以在 BSD 中工作,包括 OS X):

If you have GNU grep (it may also work in BSD, including OS X):

echo "$string" | grep -Po '\d+'

或变体,例如:

echo "$string" | grep -Po '(?<=\D )(\d+)'

-P 选项启用 Perl 兼容的正则表达式.请参阅 man 3 pcrepatternman3 pcresyntax.

The -P option enables Perl Compatible Regular Expressions. See man 3 pcrepattern or man 3 pcresyntax.

这篇关于如何仅使用 sed 输出捕获的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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