I just want to match some text in a Bash script. I've 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, it would put all the matches in an array.
edit:
Text input is coming in as a string:
newName()
{
#Get input from function
newNameTXT="$1"
if [[ $newNameTXT ]]; then
#Use code that im working on now, using the $newNameTXT string.
fi
}
You could do this purely in bash using the double square bracket
[[ ]]
test operator, which stores results in an array calledBASH_REMATCH
:I don't know why nobody ever uses
expr
: it's portable and easy.using just the bash shell
Use grep. Sed is an editor. If you only want to match a regexp, grep is more than sufficient.
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:
Here's another way:
I Know this is an old topic but I came her along same searches and found another great possibility apply a regex on a String/Variable using grep:
With using lookaround capabilities search expressions can be extended for better matching. Where
(?i)
indicates the Pattern before the searched Pattern (lookahead),\K
indicates the actual search pattern and(?=)
contains the pattern after the search (lookbehind).https://www.regular-expressions.info/lookaround.html
The given example matches the same as the PCRE regex
TestT([0-9]{3})String