再帰的に置換
カレントディレクトリにあるすべてのファイルに置換コマンドを通したいときがある。サブディレクトリも再帰的に処理したい。
そういうときのために。
シェルスクリプトでやってみる。
参考URL:http://www.shido.info/misc/misc.php?id=29
#!/bin/sh function recursiveReplace { for file in `ls $1`; do if [ $0 != ${file} ] && [ "tmp" != ${file} ]; then FULLPATH=${1}/${file} if [ -f ${FULLPATH} ]; then cp ${FULLPATH} ./tmp; tr $2 $3 < ./tmp > ${FULLPATH} elif [ -d ${FULLPATH} ]; then recursiveReplace ${FULLPATH} $2 $3 fi fi done } if [ $# -ne 2 ]; then echo "usage: $0 string1 string2" else recursiveReplace ./ $1 $2 fi
もっとスマートにgrepとsedで。
参考URL:http://d.hatena.ne.jp/himesuke/20080328/p1
% grep -rl string1 * | xargs sed -i .bak -e 's/string1/string2/g'