Skip to main content

Shell script that uses sed to find and replace matched text in multiple files.

#!/bin/sh

##
# Find and replace by a given list of files.
#
# Usage:
#
#   replace foo bar **/*.rb
#
# The first argument is the string we're finding. The second is the string with
# which we're replacing. The third is a pattern matching the list of files
# within which we want to restrict our search.
#
# Source:
# https://github.com/thoughtbot/dotfiles/blob/master/bin/replace
#
# Article:
# https://robots.thoughtbot.com/sed-102-replace-in-place
##

find_this="$1"
shift
replace_with="$1"
shift

items=$(ag -l --nocolor "$find_this" "$@")
temp="${TMPDIR:-/tmp}/replace_temp_file.$$"
IFS=$'\n'
for item in $items; do
  sed "s/$find_this/$replace_with/g" "$item" > "$temp" && mv "$temp" "$item"
done