Search code examples
bashgrep

grep out 2 field only


input text:

hello 34 others 28

I would like to run grep and get output the matched fields only:

34 28

I try below command but not as expected:

echo "hello 34 others 28" |grep -Eo "([0-9]+).*([0-9]+)"

Solution

  • You could pipe the following:

    echo "hello 34 others 28" | grep -Eo '[0-9]+' | tr '\n' ' '
    

    The matching numbers are then translated from new-line delimited values to a space separated result.

    Returns: 34 28

    You can add a positive lookbehind to tighten the matching criteria. You will have to use Perl mode instead of Extended mode. The lookbehind needs to be a fixed-width, so only a word character—follow by a space—is checked.

    echo "hello 34 others 28" | grep -Po '(?<=\w )[0-9]+' | tr '\n' ' '