有没有一种方法告诉sed只输出捕获的组?

例如,给定输入:

This is a sample 123 text and some 987 numbers

和模式:

/([\d]+)/

我能得到只有123和987输出的方式格式化后引用?


当前回答

您可以使用ripgrep,它似乎也是简单替换的sed替代品,就像这样

rg '(\d+)' -or '$1'

由于两次匹配,ripgrep使用-o或——only matching和-r或——replace两次只输出$1的第一个捕获组(引用以避免shell将其解释为变量)。

其他回答

我想给出一个关于“仅输出使用sed捕获的组”的简单示例

我有/home/me/myfile-99,并希望输出文件的序列号:99

我的第一次尝试没有成功:

echo "/home/me/myfile-99" | sed -r 's/myfile-(.*)$/\1/'
# output: /home/me/99

为了做到这一点,我们还需要捕获捕获组中不需要的部分:

echo "/home/me/myfile-99" | sed -r 's/^(.*)myfile-(.*)$/\2/'
# output: 99

*)注意sed没有\d

您可以使用ripgrep,它似乎也是简单替换的sed替代品,就像这样

rg '(\d+)' -or '$1'

由于两次匹配,ripgrep使用-o或——only matching和-r或——replace两次只输出$1的第一个捕获组(引用以避免shell将其解释为变量)。

这不是OP要求的(捕获组),但你可以使用以下方法提取数字:

S='This is a sample 123 text and some 987 numbers'
echo "$S" | sed 's/ /\n/g' | sed -r '/([0-9]+)/ !d'

给出以下内容:

123
987

您需要包含整行来打印组,这是您在第二个命令中所做的,但您不需要对第一个通配符进行分组。这也可以:

echo "/home/me/myfile-99" | sed -r 's/.*myfile-(.*)$/\1/'

放弃吧,使用Perl

既然sed不能解决这个问题,就让我们放弃并使用Perl吧,至少它是LSB,而grep GNU扩展不是:-)

Print the entire matching part, no matching groups or lookbehind needed: cat <<EOS | perl -lane 'print m/\d+/g' a1 b2 a34 b56 EOS Output: 12 3456 Single match per line, often structured data fields: cat <<EOS | perl -lape 's/.*?a(\d+).*/$1/g' a1 b2 a34 b56 EOS Output: 1 34 With lookbehind: cat <<EOS | perl -lane 'print m/(?<=a)(\d+)/' a1 b2 a34 b56 EOS Multiple fields: cat <<EOS | perl -lape 's/.*?a(\d+).*?b(\d+).*/$1 $2/g' a1 c0 b2 c0 a34 c0 b56 c0 EOS Output: 1 2 34 56 Multiple matches per line, often unstructured data: cat <<EOS | perl -lape 's/.*?a(\d+)|.*/$1 /g' a1 b2 a34 b56 a78 b90 EOS Output: 1 34 78 With lookbehind: cat EOS<< | perl -lane 'print m/(?<=a)(\d+)/g' a1 b2 a34 b56 a78 b90 EOS Output: 1 3478