Linux 複数のテキストファイルの文字列を一括で 置換するためのシェルスクリプトを作ってみました。
#!/bin/bash # ========================================================== # 複数ファイル一括置換コマンド # ----------------------------------------------------- # create : 2010/01/21 Studio ODIN # update : # ========================================================== # --- init --------------------------------------------- COMMAND_NAME=bulk_replace CUR_DIR=`pwd` # -- args ---------------------------------------------- TARGET_WORD=$1 REPLACE_WORD=$2 TARGET_DIR=$3 # -- args check ---------------------------------------- if [ "$TARGET_WORD" = "" ]; then echo "target word is nothing." >&2 echo "Usage: $0 targetword replaceword [targetpath]" >&2 exit 1 fi if [ "$REPLACE_WORD" = "" ]; then echo "replace word is nothing." >&2 echo "Usage: $0 targetword replaceword [targetpath]" >&2 exit 1 fi if [ "$TARGET_DIR" = "" ]; then TARGET_DIR=. fi # -- execute ------------------------------------------- grep -R -l "${TARGET_WORD}" "${TARGET_DIR}" | while read file do tfile=`mktemp -u` cp -f -p $file $tfile > /dev/null 2>&1 if [ $? -eq 0 ]; then sed -e "s/${TARGET_WORD}/${REPLACE_WORD}/g" $file > $tfile if [ $? -ne 0 ]; then echo "Warning: failed write '$file'" fi mv -f $tfile $file > /dev/null 2>&1 if [ $? -ne 0 ]; then echo "Warning: failed rewrite '$file'" rm -f $tfile > /dev/null 2>&1 fi else echo "Warning: failed copy '$file'" fi done # -- normal end ---------------------------------------- cd $CUR_DIR exit 0 # ========================================================== # shell end # location: /usr/local/bin/bulk_replace # ==========================================================
実行する場合は、パスの指定など大事なファイルが 大変なことにならないように気を付けてください。 (自己責任でお願いします)
こんなコマンドは、すでにあるような気もしますが 自分で処理を考えて作ってみるのは面白いと思います。