Search code examples
bashsedgreptext-manipulation

How can I output the number on the nth position in a string?


Using bash, lets say i have the following string

string="Same bought 5 bananas, 12 apples, 2 peaches and 16 oranges"

How can I trim everything except the nth number. In this case I want to output 12 which is the second number in the string.

How can I do that with bash, grep or sed?


Solution

  • Solution Using sed

    According to Paul Hodges and Triplee grep -Eo '[0-9]+' <<<"$string"| sed 'nq;d'


    Where n is the position of the number

    sed 'NUMq;d'
    NUM is the lines to print.
    2q says quit on the second line.
    d will delete every other line except the last