Return a regex match in a BASH script, instead of replacing it


I just want to match some text in a BASH script, i’v tried using sed, but I can’t seem to make it just output the match instead of replacing it with something.

echo -E "TestT100String" | sed 's/[0-9]+/dontReplace/g'

Which will output: TestTdontReplaceString

Which isn’t what I want, I want it to output: 100

Ideally I would want it to put all the matches in an array.

edit: Text input is coming in as a string:

 #Get input from function

 if [[ $newNameTXT ]]; then
 #Use code that im working on now, using the $newNameTXT string.

12/14/2009 2:26:40 AM

Accepted Answer

echo "TestT100String" | sed 's/[^0-9]*\([0-9]\+\).*/\1/'

echo "TestT100String" | grep -o  '[0-9]\+'

The method you use to put the results in an array depends somewhat on how the actual data is being retrieved. There's not enough information in your question to be able to guide you well. However, here is one method:

while read -r line
    array[index++]=$(echo "$line" | grep -o  '[0-9]\+')
done < filename

Here's another way:

array=($(grep -o '[0-9]\+' filename))
12/14/2009 2:24:37 AM

You could do this purely in bash using the double square bracket [[ ]] test operator, which stores results in an array called BASH_REMATCH:

[[ "TestT100String" =~ ([0-9]+) ]] && echo "${BASH_REMATCH[1]}"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow