置換リストに従って、あるフォルダ以下の全てのファイルの該当文字列を置換するシェルスクリプト

初心者です。

#!/bin/sh

list=./replace_list.txt
target=./target_dir

cd `dirname $0`
LC_ALL=C

cat $list | while read -r line
do
    before=$(awk '{print $1}' <<< $line)
    after=$(awk '{print $2}' <<< $line)

    grep -rl "${before}" $target | xargs sed -i '' -e "s/${before}/${after}/g"
done

replace_list.txt は単にスペースで置換前の文字列と置換後の文字列を並べます。

hoge piyo
foo bar
moo meh

cd `dirname $0` はそのスクリプトの存在するディレクトリに移動するためのイディオムで、個人的によく使います。

LC_ALL=CはMacの場合のみ必要で、sedがエラーを出す問題の回避のためです。

dqn.sakusakutto.jp