1

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.

0

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Parameter expansion is excellent. The BASH_REMATCH is much better than an external solution like sed 's/[.]config.*//' <<< "${string}".
@WalterA Depending on size of files to work on! Using dedicated tasks to do specialized function (like sed) permit parallelization, then become much more quick! Have a look at best way to divide in bash for a sample of dedicated parallel task!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.