Shell Script To Find & Replace Text Within Multiple Files In A Directory Using 'sed' Command

I'm writing this post simply for the purpose of reminding myself of how I built my first shell script... I'm not sure if admitting this is a positive or negative thing. Writing shell scripts has never truly been a part of my day-to-day work, but understood the core concepts and what they are able to do.

I decided to write this shell script to perform a rather easy task: cycle through all CSS and JS files in a directory and change a string within each file with the value that was entered into the shell script. The main use of this script, for my use, is to update path references in these files.

# Script Name: CSS/JS Path Replacer #
# Description: Iterates through all directories to replace strings found in CSS and JS files. #
#               Place this bash script in the directory where the files reside. #
#               For example: /resources. #

# Take the search string.
read -p "Enter the search string: " search

# Take the replace string.
read -p "Enter the replace string: " replace

FILES="./**/*.min.css ./**/*.css ./**/*.min.js ./**/*.js"

for f in $FILES
do
    echo "Processing $f file..."
  
    sed -i "s/${search//\//\\/}/${replace//\//\\/}/g" $f
done

$SHELL

To carry out a replace within each file, I'm using the sed command:

sed -i "s/old-value/new-value/g" filename.txt

This command tells sed to find all occurrences of "old-value" and replace with "new-value" in a file called "filename.txt". As the main purpose of the script is to update path references within CSS and JS files, I had to escape forward slashes in the "search" and "replace" variables when parsed to the sed command.

Bash script in use:

Enter the search string: /surinder-v1/resources
Enter the replace string: /surinder-v2/resources
Processing ./css/site.min.css file...
Processing ./css/site.css file...
Processing ./css/site.min.css file...
Processing ./css/styleguide.css file...
Processing ./js/global.min.js file...
Processing ./js/global.min.js file...

Once the script has processed all the files, any reference to "/surinder-v1/resources" will be replaced with "/surinder-v2/resources".

Further useful information about using the "sed" command can be found in the following post: How to use sed to find and replace text in files in Linux / Unix shell.


Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee


Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself. :-)