Find and replace

Here’s my little bash script to find and replace a text string in a file using sed (it’s longer than the command line input needed to just run sed, but is a bit easier to remember and means I don’t have to google the correct method every time I want to use it!):

#! /bin/bash

# little script to do find and replace on a file using sed
# Usage: ./find_replace.sh filename FINDSTRING REPLACESTRING

# it uses sed via: sed -i 's/FINDSTRING/REPLACESTRING/g' filename

fname=$1
fstring=$2
rstring=$3

sed -i "s/$fstring/$rstring/g" $fname

echo Replaced $fstring with $rstring in $fname

Leave a Reply