Published on

Search and Replace in Bash script

Authors

I recently had a colleague ask me how to do in-line regular expression matching for a Bash shell script. Since Bash v3 only offers a regex matching check and not the full s/foo/bar/ regex syntax, I offered to look into other alternatives.

My natural instinct was to look for a Perl cmdline regex parser, which works great if you're manipulating a file and not shell variables.

In the end, since he only needed a simple search and replace, and not an actual regular express, this sufficed:

#!/bin/bash
VAR1="foobar"
VAR2=`echo $VAR1 | awk -v srch="foo" -v repl="bar" '{ sub(srch,repl,$0); print $0 }'`

echo $VAR1
echo $VAR2