Sunday, February 19, 2012

Bash string replace

I was using sed for template substitution recently and it seemed that no matter what regex delimiter I chose, that char existed in the template and caused my template population (sed replace) to fail. Fortunately bash has string substitution built right in, albeit with some slightly strange syntax.

# replace all @ chars with \@
x=${x//@/\\@}

now we can freely sub in values for our template variables w/o having to worry if they contain @ characters

#$1 = file name
#$2 = template variable name
sed -i s@$2@$x@g templates/$1



No comments:

Post a Comment