通过bat,shell脚本读取properties配置文件拼接字符串

通过bat,shell脚本读取properties配置文件拼接字符串

  • 1. bat script
  • 2. shell script

1. bat script

@echo off

:: 读取配置文件
echo ====== toman-archetype ======
echo Reading configuration file config.properties

setlocal EnableDelayedExpansion
:: eol=#: 忽略注释行 tokens:取第1,2列,第一列%%i,第二列%%j delims==:每行以=分割
for /f "eol=# tokens=1,2 delims==" %%i in (config.properties) do (

    set key=%%i

    ::trim left whitespace
    for /f "tokens=* delims= " %%a in ("!key!") do set key=%%a
    ::trim right whitespace (up to 100 spaces at the end)
    for /l %%a in (1,1,100) do if "!key:~-1!"==" " set key=!key:~0,-1!

    set value=%%j

    ::trim left whitespace
    for /f "tokens=* delims= " %%a in ("!value!") do set value=%%a
    ::trim right whitespace (up to 100 spaces at the end)
    for /l %%a in (1,1,100) do if "!value:~-1!"==" " set value=!value:~0,-1!

    :: 拼接参数
    set params=!params! -D!key!=!value!

    :: 打印所有的属性配置
    echo !key! : !value!
)

:: 打印参数
echo !params!

:: 生成项目结构
:: set MAVEN_HOME=D:\jd-dev-env\apache-maven-3.5.4
%MAVEN_HOME%\bin\mvn archetype:generate -B !params!

pause

2. shell script

#!/bin/bash

echo ======= toman-archetype ======

echo Read configuration file config.properties

# 定义数组 CONFIG
declare -A CONFIG
# IFS is the 'internal field separator'. In this case, your file uses '='
IFS="="
while read -r key value
do
    # trim key
    ckey=`echo $key |sed "s/^[ \s]\{1,\}//g;s/[ \s]\{1,\}$//g"`
    # trim value
    cvalue=`echo $value |sed "s/^[ \s]\{1,\}//g;s/[ \s]\{1,\}$//g"`
    
    # 如果key不是以空格开始而且不是以#开始,则认为是有效行,将配置信息保存到数组中
    if [[ $ckey =~ [^[:space:]] ]] && [[ $ckey != \#* ]]
    then
        CONFIG[$ckey]=$cvalue
    # 打印有效配置信息
    echo $ckey : $cvalue
    # 拼接参数
    params=`echo "$params -D$ckey=$cvalue"`
    fi
done < config.properties
unset IFS

# 打印参数
echo $params

# 设置环境变量
# export MAVEN_HOME=D:\jd-dev-env\apache-maven-3.5.4
# 执行Maven命令
${MAVEN_HOME}\bin\mvn archetype:generate -B $params

pause

你可能感兴趣的:(通过bat,shell脚本读取properties配置文件拼接字符串)