Bash shell script return first number / integer from multiline variable?

The string may contain "N/A" at any given location, I simply need to use the first returned integer/number in the script I am working on.

example:

STRING="N/A"$'\n'"77"$'\n'"66"$'\n'"222"
echo "${STRING}"
echo "${STRING//[!0-9]/}"

returns: 7766222

desired output is: 77

this gave some useful information: https://linuxconfig.org/how-to-extract-a-number-from-a-string-using-bash-example

1 answer

  • answered 2018-11-07 22:58 oguzismail

    Using sed

    $ sed '/^[0-9]\+$/q;d' <<< "$STRING"
    77
    

    Using awk

    $ awk '/^[0-9]+$/{print;exit}' <<< "$STRING"
    77