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

例如,给定输入:

This is a sample 123 text and some 987 numbers

和模式:

/([\d]+)/

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


当前回答

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

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

其他回答

你可以使用grep

grep -Eow "[0-9]+" file

放弃吧,使用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

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

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

Try

sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

我在cygwin下得到了这个:

$ (echo "asdf"; \
   echo "1234"; \
   echo "asdf1234adsf1234asdf"; \
   echo "1m2m3m4m5m6m7m8m9m0m1m2m3m4m5m6m7m8m9") | \
  sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

1234
1234 1234
1 2 3 4 5 6 7 8 9
$

这不是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