shell 實現ini文件的讀寫

直接上代碼:

#!/bin/bash

filepath=/root/test.txt

#$1 filename
#$2 group
#$3 key
#


fun_get_value(){
#How to use:fun_get_value filepath key
is_group=0
while read line
do
    group_str=$(echo "$line"  | grep -n '\[*\]' | awk -F "[" '{print $2}' | awk -F "]" '{print $1}')
    if [[ -n "$group_str" ]];then

        if [[ "$group_str" = "$2"  ]];then
            is_group=1
        else
            is_group=0
        fi
    fi
    if [[ "$is_group" = "1" ]];then
        if [[ "${line:0:1}" != "#" ]];then
            if [[ "$(echo "$line" | awk -F '=' '{print $1}')" = "$3" ]];then
                echo "$(echo "$line" | awk -F '=' '{print $2}')"
            fi
        fi
    fi
done <<< "$(cat $1)"
}

fun_set_value(){
#How to use:fun_set_value filepath key value
lines_id=0
is_group=0
while read line
do
    lines_id=`expr $lines_id + 1`
    group_str=$(echo "$line"  | grep -n '\[*\]' | awk -F "[" '{print $2}' | awk -F "]" '{print $1}')
    if [[ -n "$group_str" ]];then

        if [[ "$group_str" = "$2"  ]];then
            is_group=1
        else
            is_group=0
        fi
    fi
    if [[ "$is_group" = "1" ]];then
        if [[ "${line:0:1}" != "#" ]];then
            if [[ "$(echo "$line" | awk -F '=' '{print $1}')" = "$3" ]];then
                break
            fi
        fi
    fi
done <<< "$(cat $1)"

sed -i "${lines_id}s/${3}=.*/${3}=${4}/g" $1

}

#value1=$(fun_get_value $filepath "yuyu" "33")
#echo "value1:$value1"

fun_set_value $filepath "yuyu" "uu" "789"

測試文件:

[root@localhost ~]# cat test.txt 
#fjslfj;afls;jflsjafl;ajfl;safdl;jjflsflsas

[yuyu]
kk=00
#fjslfj;afls;jflsjafl;ajfl;safdl;jjflsflsas
uu=789
33=ZZpp
033=rr

#fjslfj;afls;jflsjafl;ajfl;safdl;jjflsflsas
[uyyu]
kk=00
uu=tytyt
33=79794656
033=rr
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章