Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 } 
like image 356
Mint Avatar asked Dec 14 '09 01:12

Mint


People also ask

How do I match a regular expression in bash?

To match regexes you need to use the =~ operator.

How do I change a pattern in bash?

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.

How do I use regex to match?

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).

What does =~ mean in bash?

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.


2 Answers

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]}" 
like image 70
John Kugelman Avatar answered Sep 20 '22 03:09

John Kugelman


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)) 
like image 20
Dennis Williamson Avatar answered Sep 20 '22 03:09

Dennis Williamson