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 }
To match regexes you need to use the =~ operator.
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.
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]}"
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:
index=0 while read -r line do array[index++]=$(echo "$line" | grep -o '[0-9]\+') done < filename
Here's another way:
array=($(grep -o '[0-9]\+' filename))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With