Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass the matched value to a function, and replace with the return value

Tags:

regex

bash

sed

awk

How would I get Bash to match a regular expression, but rather than replace the value with a constant string, it will instead pass the matched value to a function, and then get the value to replace with from the return value of the function.

Something like the following pseudocode, which replaces every match of [a-d] with the same character, but uppercase:

function uppercase() { echo ${1^^}; }
string="abcdefgh123cbazyz"
echo ${string//[a-d]/uppercase()}
# output: ABCDef123CBAzyz

I'm not particular, any language that is typically installed on a Unix system (such as sed, awk, or even the limited regex support built into bash) can be used.

like image 901
IQAndreas Avatar asked Aug 06 '26 17:08

IQAndreas


1 Answers

Bash can't use user defined functions inside parameter expansion.

To accomplish what you want, use pattern matching with case modification:

string="abcdefgh123cbazyz"
echo ${string^^[a-d]}

Output:

ABCDefgh123CBAzyz
like image 59
John B Avatar answered Aug 08 '26 11:08

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!