`
steven-zhou
  • 浏览: 207869 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

bash实现:对配置文件的增、删、改

    博客分类:
  • Bash
阅读更多
#!/bin/sh
#
# Name: add_del_mod.sh configure file operation script.
#
# Version:  1.0.0   05-Dec-2008
# Author :  tcaosmail@gmail.com
#
# Description:
#   add, delete and modify specified record in a
#   configure file according to parameters.
#
# Synopsis: add_del_mod FILE [ADD|DEL|MOD] [ROW_NUM] [LINE_CONTENT]
#
# Examples:
#   add_del_mod /etc/ipsecmc/userip.conf ADD 1 "olymuser 123456 192.168.135.1"
#   add_del_mod /etc/ipsecmc/userip.conf MOD 1 "olymuser 123456 10.0.0.1"
#   add_del_mod /etc/ipsecmc/userip.conf DEL 1
#
[ "$#" -lt "3" ] && echo "too few parameters!" && exit 1

FILE="$1"
ACTION="$2"
NROW="$3"
TMPFILE="$FILE-$$"

# check file exist or not.
[ ! -e "$FILE" ] && echo "FILE: [$FILE] not exist!" && exit 1
# check row number is a pure number.
[ `echo $NROW | grep -c '^[0-9]*$'` != 1 ] && echo "ROW_NUM: [$NROW] is not digit!" \ 
&& exit 1

case "$ACTION" in
    "ADD")
        [ "$#" != "4" ] && echo "too few parameters for action [ADD]!" && exit 1
        if [ "$NROW" == "0" ]; then # append to the end of file.
            echo "$4" >> $FILE
        else
            cat $FILE | grep -v '^$' | sed "${NROW}i $4" > $TMPFILE
            mv $TMPFILE $FILE
        fi
        ;;
    "MOD")
        [ "$#" != "4" ] && echo "too few parameters for action [MOD]!" && exit 1
        cat $FILE | grep -v '^$' | sed "${NROW}c $4" > $TMPFILE
        mv $TMPFILE $FILE
        ;;
    "DEL")
        cat $FILE | grep -v '^$' | sed "${NROW}d" > $TMPFILE
        mv $TMPFILE $FILE
        ;;
    *)
        echo "action [$ACTION] invalid!"
        exit 1
        ;;
esac

exit 0
分享到:
评论
2 楼 steven-zhou 2008-12-15  
主要是想提供一个增、删、改的统一接口,给C程序调用。
1 楼 wosmvp 2008-12-15  
直接使用sed不更好吗?

相关推荐

Global site tag (gtag.js) - Google Analytics