ホーム » Tips集 » Shell » rewrite.sh

Tips集

rewrite.sh

  • コマンド(command_A)+ファイル名(file_B)を引数に取る
  • file_B に対する command_A の出力結果を引数ファイルに上書きする。
  • ex.1) rewrite.sh nkf -w sjis.txt (文字コードの変更)
  • ex.2) rewrite.sh sed s/aaa/bbb/g ABC.txt (文字置換)
  • ex.3) rewrite.sh sort -n reverse.txt (ソート)
#!/bin/bash
#$Id: rewrite.sh,v 1.10 2014-01-08 14:09:47+09 shirai Exp $

rewrite(){
	all=()
	check_options $@
	file="${all[$((${#all[@]}-1))]}"
	file_checker $file
	tmp="TEMP_${file##*/}"
	${all[@]} > $tmp
	if [ $SaveTimeStamp = 1 ]; then
		touch -r $file $tmp
	fi
	if [ -x $file ]; then
		chmod +x $tmp
	fi
	if [ $? = 0 ];then
		mv $tmp $file
		echo "---> $file was rewriten"
	else
		echo " $0 was failed"
		rm $tmp
	fi
}

check_options(){
usage_msg="\
Usage: $0 [options] files

Options:
  -h		show this help
  -s		save time stamp
"
	
	SaveTimeStamp=0
	while getopts hs option
	do
		case "$option" in
		h)
			echo "$usage_msg"
			exit 0
			;;
		s)
			SaveTimeStamp=1
			;;
		\?)
			echo "Usage: $0 [-h] [-s] command files" 1>&2
			exit 1;;
		esac
	done
	shift `expr "$OPTIND" - 1`


	if [[ $# < 2 ]];then
		echo " PLEASE INPUT  COMMAND  AND  FILE" 1>&2
		echo "$usage_msg" 1>&2
		exit 1
	fi
	all=($@)
}

file_checker(){
(
	file=$1
	if [ ! -f $file ]; then
		echo "$file does not exist."
		exit 1
	fi
)
}

rewrite $@

おすすめソフト