[Linux]Shell脚本实现按照模块信息拆分文件内容

示例conf_file文件内容如下

[root@CSDN /home/Sudley/get_conf_info]#cat conf_file
<module_1> info start==
name:lt
address:North
phone:10086
tx.rpm
<module_1> info end==
<module_2> info start==
#nothing
<module_2> info end==
<module_3> info start==
name:yd
address:South
phone:10010
al.rpm
<module_3> info end==

conf_file文件包含module_1、module_2、module_3,module_2没内容,编写脚本将conf_file文件拆分为module_1、module_3两个模块(module_2没内容,不做处理)
代码实现:

#!/bin/bash
# Author:Sudley
# ctime: 2020-05-31

get_conf_info()
{
        conf_file="$1"
        flag="$2"
        if [ ! -f "${conf_file}" ] || [[ -z "${flag}" ]];then
                echo "argument error"
                echo "usage:"
                echo "    ./get_conf_info.sh conf_file flag "
        fi

        print_flag=false
        while read line
        do
                #无视注释的行
                echo "${line}" | grep "^ *#.*" > /dev/null 2>&1 && continue

                if [[ "${line}" =~ "${flag} start==" ]];then
                        module_name=$(echo "${line#<}"|awk -F '>' '{print $1}')
                        print_flag=true
                        continue
                fi
                if [[ "${line}" =~ "${flag} end==" ]];then
                        print_flag=false
                        continue
                fi

                if [ "${print_flag}" = true ];then
                        echo "${line}" >> "${WORKSPACE}/${module_name}"
                fi

        done < "${conf_file}"

}

get_address_rpms()
{
        label="address"
        grep "${label}" "${WORKSPACE}" -rn |awk -F : '{print $1}' >> "${WORKSPACE}/module.list"
        while read module
        do
                grep ".*\.rpm$" "${module}"
        done < "${WORKSPACE}/module.list"
}

export BASE_DIR=`pwd`
export WORKSPACE="${BASE_DIR}/workspace_t"
[[ -d "${WORKSPACE}" ]] && rm -rf "${WORKSPACE}"
mkdir -p "${WORKSPACE}"
get_conf_info "$1" "$2"
get_address_rpms

脚本用法演示:
[Linux]Shell脚本实现按照模块信息拆分文件内容_第1张图片

你可能感兴趣的:(Linux)