Search and Replace in Bash script

The blog is currently being ported from WordPress to over 12 years of static pages of content. If there's an article missing that you're hoping to see, please contact me and let me know and I'll prioritize getting it online.

July 28, 2011


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

image credit: https://tiswww.case.edu/php/chet/bash/bashtop.html