批量处理文件内容脚本

#!/bin/bash
set -e

prefix=$1

#fname='(-iname "type1_*.sql" -or -iname "type2_*.sql" -or -iname "type3_*.sql" -or -iname "type9_*.sql" -or -iname "type13_*.sql" -or -iname "type14_*.sql")'

root=$2
if [ -z "$prefix" ];then
echo prefix is null;
exit
fi
if [ -z "$root" ];then
root="./"
fi

cd $root

count=0;
groups="";

writeline(){
    count=`expr $count + 1`
    local fpath=$1
    echo $fpath
    # 组名
    local group=$2
    groups="${groups} ; ${group}"
    # 获取文件名
    local name=${fpath#*type*_}
    name=${name%%\.sql*}
    #替换单引号 '  为  \'
    sed "s/'/\\\'/g" ${fpath} > $root/temp

    sed -i "" "s/2018-04-01/{{PRE_MONTH_FIRST_DAY}}/g" $root/temp 
    sed -i "" "s/2018-04-19/{{PRE_PERIOD_FIRST_DAY}}/g" $root/temp 
    sed -i "" "s/2018-04-25/{{PRE_WEEK}}/g" $root/temp 
    sed -i "" "s/2018-04-26/{{CUR_PERIOD_FIRST_DAY}}/g" $root/temp 
    sed -i "" "s/2018-04-30/{{PRE_MONTH_LAST_DAY}}/g" $root/temp 
    sed -i "" "s/2018-05-02/{{RP_TODAY}}/g" $root/temp 


    local sql=`cat $root/temp`
    # sql=${sql//\'/\\\'}
    # result="${result}\n |0| ${name} |1| ${group} |2| '${sql//\'/\\\'}' |3|"


    if [ -z "$result" ];then
    result="('${name}','${group}','${sql}','${fpath}')"
    else
    result="${result},\n('${name}','${group}','${sql}','${fpath}')"
    fi
}

dive(){
    local dirs=$1
    local group=$2
    if [ -z "$dirs" ]; then return;fi

    for dir in ${dirs[@]}
    do
        if [ -d "${dir}" ];then
        #获取最后一级目录
        group=${dir##*/}
        dive "`find ${dir} -maxdepth 1  -mindepth 1 \( -iname "${prefix}_*.sql" -or -type d \)`" ${group}
        else
          writeline "${dir}" ${group}
        fi
    done
}

dive "`find . -maxdepth 1  -mindepth 1 \( -iname "${prefix}_*.sql" -or -type d \)`"
head="INSERT INTO spt_script ( name, group_name, script,descr) VALUES"
result="#groups:${groups}\n#======\n#count:${count}\n#========\n${head}\n${result};"

echo -e "${result}">${prefix}-export.sql
echo ${count}

Last updated