记得刚进公司的时候被大佬要求用shell写一个 xml 读写工具 要求符合 xxx.xx.xx 的父子节点关系
代码如下分享一下
写入xml
#!/bin/sh
array=""
index=0
i_count=1
function set_xml_value()
{
if [[ ! -n $1 || ! -n $2 || ! -n $3 ]]
then
echo "[ERROR] 参数错误:[$1] [$2] [$3]"
return
fi
local string=$1
local value=$2
local file_name=$3
local split=(${string//./ })
let count=0
for var in ${split[@]}
do
array[$count]=$var
((count=count+1))
done
local file_len=$(wc -l $file_name | awk -F ' ' '{print $1}')
count=1
while read LINE
do
key=$(get_check_key)
ret=$(echo $LINE | sed -n "/<$key>/p" | wc -l)
if (( $ret == '1' )); then
if (( $i_count == ${#array[@]} ))
then
set_check_key
break
fi
set_check_key
fi
((count=count+1))
done<$file_name
if (( $count >= $file_len ))
then
echo "[ERROR] 错误配置:$1 节点$(get_check_key)不存在"
return
fi
sed -i "$count s/>.*</>$value</" $file_name
}
function get_check_key()
{
echo ${array[$index]}
}
function set_check_key()
{
((index=index+1))
((i_count=i_count+1))
}
function test_array()
{
for element in ${array[@]}
do
echo $element
done
}
set_xml_value $1 $2 $3
读取
#!/bin/sh
array=""
index=0
i_count=1
function get_xml_value()
{
if [[ ! -n $1 || ! -n $2 ]]
then
error "[ERROR] 参数错误:[$1] [$2]"
return
fi
local string=$1
local file_name=$2
local split=(${string//./ })
let count=0
for var in ${split[@]}
do
array[$count]=$var
((count=count+1))
done
local file_len=$(wc -l $file_name | awk -F ' ' '{print $1}')
count=1
while read LINE
do
key=$(get_check_key)
ret=$(echo $LINE | sed -n "/<$key>/p" | wc -l)
if (( $ret == '1' )); then
if (( $i_count == ${#array[@]} ))
then
set_check_key
break
fi
set_check_key
fi
((count=count+1))
done<$file_name
if (( $count >= $file_len ))
then
error "[ERROR] 错误配置:$1 节点$(get_check_key)不存在"
return
fi
sed -n "$count,$count p" $file_name | awk -F'>' '{print $2}' | awk -F '<' '{print $1}'
}
function get_check_key()
{
echo ${array[$index]}
}
function set_check_key()
{
((index=index+1))
((i_count=i_count+1))
}
function test_array()
{
for element in ${array[@]}
do
echo $element
done
}
get_xml_value $1 $2