Tips集
change_names.sh
- プログラムの名前と内容を変更するスクリプト
- 同一ディレクトリにある複数のファイルに作用する
- 例えば ProgramA.h ProgramB.c ProgramC.c という同じディレクトリ内にある3つのファイル名を prgA.h prgB.c prg.c へと変更し、さらに元の3つのファイル中に含まれる“Program“という記述も“prg“へと変更したい時に使用する
- [オプション]
- 引数1= 変更前のプロジェクトネーム (例. Program)
- 引数2= 変更後のプロジェクトネーム (例. prg)
- [作成意図] Makefile などに含まれるファイル名も同時に変更してくれる
- [注意] プログラム内の意図しない文字列も置換されてしまう可能性がある。例えば “a” を “A” に変えるなどをすると、プログラム中の全てのaがAに変わってしまう
#!/bin/bash
# $Id: change_names.sh,v 1.2 2014-01-03 17:09:59+09 shirai Exp shirai $
before="$1"
after="$2"
main(){
before=""
after=""
file=""
check_options $@
first_mod
second_mod
echo " finished !"
}
check_options(){
usage_msg="\
Usage: $0 [options] files
Options:
-h show this help
"
SaveTimeStamp=0
while getopts hs option
do
case "$option" in
h)
echo "$usage_msg"
exit 0
;;
\?)
echo "Usage: $0 [-h] command files" 1>&2
exit 1;;
esac
done
shift `expr "$OPTIND" - 1`
before="$1"
after="$2"
file=$3
if [[ "$before" == "" || "$after" == "" ]];then
echo " PLEASE INPUT TWO WORDS FOR sed" >&2
echo "Usage: $0 present_name new_name" >&2
exit 1
fi
}
first_mod(){
echo "[1] first modification start!"
list=(`fls`)
#list=(`ls`)
list=(`grep -l $before ${list[@]}`)
for file in ${list[@]}; do
sed_rewrite_-s $before $after $file
done
}
second_mod(){
echo "[2] second modification start!"
#list=(`fls`)
list=(`ls`)
for file in ${list[@]}; do
check_word=(`echo $file | grep -c ${before}`)
if ((check_word>0)); then
diae mv $file ${file%${before}*}${after}${file#*${before}}
fi
done
}
sed_rewrite_-s(){
if [[ $# < 3 ]];then
echo " PLEASE INPUT TWO WORDS AND FILE" >&2
echo " Usage: $0 word1 word2 file" >&2
exit 1
fi
word1=$1
word2=$2
file=$3
tmp="TEMP_${file##*/}"
sed "s@$word1@$word2@g" $file > $tmp
touch -r $file $tmp
if [ -x $file ]; then
chmod +x $tmp
fi
if [ $? = 0 ];then
mv $tmp $file
echo "---> $file was rewriten"
else
echo " sed was failed"
rm $tmp
fi
}
diae(){
echo $@
$@
}
fls(){
ls -F $@ | grep -v / | sed "s@\*@@g"
}
main $@