字符处理函数
#!/bin/bash
# example:
# replacevariables func @x vara
# assume func=@x*@x+2*@x+1 vara=(a b c)
# to apply @x as a,b,c in func, the result is a*a+2*a+a b*b+2*b+1 c*c+2*c+1
function replacevariables
{
if [[ $# -ne 3 ]]; then
return ;
fi
local functionstr=$1
local var=$2
local appvararray
eval appvararray=(\${$3[@]})
local resultarray
local appvar
local i=0
for appvar in ${appvararray[@]}; do
resultarray[${i}]=`echo ${functionstr} | sed "s/${var}/${appvar}/g"`
((i++))
done
echo ${resultarray[@]}
}
# example:
# combinearray vara varb ${hyphen}
# assume vara=(a b c) varb=(x y z) hyphen=+
# the result is a+x b+y c+z
function combinearray
{
if [[ $# -ne 3 ]]; then
return ;
fi
local vararray1
local vararray2
eval vararray1=(\${$1[@]})
eval vararray2=(\${$2[@]})
local hyphen=$3
local resultarray
local length
((length=(${#vararray1[@]}<${#vararray2[@]}?${#vararray1[@]}:${#vararray2[@]})))
local i
for ((i=0;i<${length};i++)) ; do
eval resultarray[${i}]=\${vararray1[${i}]}${hyphen}\${vararray2[${i}]}
done
echo ${resultarray[@]}
}
# example:
# arraytostring vara hyphen
# assume vara=(a b c) hyphen=+
# the return result is a+b+c
function arraytostring
{
if [[ $# -ne 2 ]]; then
return ;
fi
local vararray
eval vararray=(\${$1[@]})
local result=""
local hyphen=$2
local temphyphen=""
local var
for var in ${vararray[@]} ; do
result=${result}${temphyphen}${var}
temphyphen=${hyphen}
done
echo ${result}
}