Jieiku
Jieiku

Reputation: 519

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

Upvotes: 0

Views: 122

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

Using sed

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

Using awk

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

Upvotes: 1

Related Questions