chanwcom
chanwcom

Reputation: 4680

How to find a specific portion of a string using a regular expression in bash

I would like to find a specific portion of a string using a regular expression in bash. Additionally, I would like to store that portion in another bash variable. By searching in the web, I could find one solution:

#!/bin/bash

string="aaa.ddd.config.uuu"
result=`expr match "$string" '\(.*\)\.config.*'`
echo $result

In the above case, I would like to find out the portion before "\.config" and want to store in another variable named result. Is the above one a good and efficient approach? I would like to know what would be a recommended way in such cases.

Upvotes: 1

Views: 56

Answers (2)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 71047

Avoid bash regex when not needed

Use:

result=${string%.config*}

Not only quicker, but more POSIX compliant.

Tests:

string="aaa.ddd.config.uuu"

time for ((i=30000;i--;)){ [[ $string =~ (.*)\.config ]] && result=${BASH_REMATCH[1]} ;}

real    0m1.331s
user    0m1.313s
sys     0m0.000s

echo $result 
aaa.ddd

Ok

time for ((i=30000;i--;)){ result=${string%.config*} ;}

real    0m0.226s
user    0m0.224s
sys     0m0.000s

echo $result 
aaa.ddd

For this, bash regex will take 5.8x more resources than simple Parameter Expansion!

Upvotes: 2

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136515

You can use bash built-in regular expressions and the array variable BASH_REMATCH that captures the results of a regular expression match:

$ string="aaa.ddd.config.uuu"
$ [[ $string =~ (.*)\.config ]] && result=${BASH_REMATCH[1]} 
$ echo $result
aaa.ddd

Upvotes: 2

Related Questions