Searching and replacing keywords in Bash
by John M. Higgins
Jul 28, 2025
Here's a script that helps you search and replace keywords in Bash:
#!/usr/bin/env sh
if test -z "$1" || test -z "$2" || test -z "$3"; then
echo 'usage: replaceall FILEPATH_REGEX BEFORE AFTER'
exit 1;
fi
find . -type f | grep -E "$1" | xargs -I '{}' sed -i "s/$2/$3/g" '{}'
It takes three arguments: a regex that matches file paths, a pattern that matches text and a pattern that will replace the text.
EXAMPLE: say that I am writing a web UI with TailwindCSS. I have the background of several buttons configured to be bg-blue-500. If I want to change them from blue to green can run this command to replace all instances of bg-blue-500 found in HTML files with bg-green-500:
./replaceall *\.html bg-blue-500 bg-green-500
NOTE: the file pattern is a regular expression so you will have to escape certain characters if you want them to be interpreted literally and not as part of a special pattern.