簡體   English   中英

如何使用 Shell 腳本讀取包含具有句點字符的鍵的 .properties 文件

[英]How to read a .properties file which contains keys that have a period character using Shell script

我正在嘗試從包含句點 (.) 字符的 shell 腳本中讀取屬性文件,如下所示:

# app.properties
db.uat.user=saple user
db.uat.passwd=secret


#/bin/sh
function pause(){
   read -p "$*"
}

file="./app.properties"

if [ -f "$file" ]
then
    echo "$file found."
 . $file

echo "User Id " $db.uat.user
echo "user password =" $db.uat.passwd
else
    echo "$file not found."
fi

我試圖在獲取文件后解析文件,但它不起作用,因為鍵包含“。” 字符並且該值中也有空格。

我的屬性文件始終位於腳本的同一目錄中或 /usr/share/doc 中的某個位置

我在 bash 腳本中使用簡單的grep內部函數來接收來自.properties文件的屬性。

我在兩個地方使用這個屬性文件 - 設置開發環境和作為應用程序參數。

我相信grep在大循環中可能會運行緩慢,但是當我想准備dev環境時它可以解決我的需求。

希望有人會發現這很有用。

例子:

文件: setup.sh

#!/bin/bash

ENV=${1:-dev}

function prop {
    grep "${1}" env/${ENV}.properties|cut -d'=' -f2
}

docker create \
    --name=myapp-storage \
    -p $(prop 'app.storage.address'):$(prop 'app.storage.port'):9000 \
    -h $(prop 'app.storage.host') \
    -e STORAGE_ACCESS_KEY="$(prop 'app.storage.access-key')" \
    -e STORAGE_SECRET_KEY="$(prop 'app.storage.secret-key')" \
    -e STORAGE_BUCKET="$(prop 'app.storage.bucket')" \
    -v "$(prop 'app.data-path')/storage":/app/storage \
    myapp-storage:latest

docker create \
    --name=myapp-database \
    -p "$(prop 'app.database.address')":"$(prop 'app.database.port')":5432 \
    -h "$(prop 'app.database.host')" \
    -e POSTGRES_USER="$(prop 'app.database.user')" \
    -e POSTGRES_PASSWORD="$(prop 'app.database.pass')" \
    -e POSTGRES_DB="$(prop 'app.database.main')" \
    -e PGDATA="/app/database" \
    -v "$(prop 'app.data-path')/database":/app/database \
    postgres:9.5

文件: env/dev.properties

app.data-path=/apps/myapp/

#==========================================================
# Server properties
#==========================================================
app.server.address=127.0.0.70
app.server.host=dev.myapp.com
app.server.port=8080

#==========================================================
# Backend properties
#==========================================================
app.backend.address=127.0.0.70
app.backend.host=dev.myapp.com
app.backend.port=8081
app.backend.maximum.threads=5

#==========================================================
# Database properties
#==========================================================
app.database.address=127.0.0.70
app.database.host=database.myapp.com
app.database.port=5432
app.database.user=dev-user-name
app.database.pass=dev-password
app.database.main=dev-database

#==========================================================
# Storage properties
#==========================================================
app.storage.address=127.0.0.70
app.storage.host=storage.myapp.com
app.storage.port=4569
app.storage.endpoint=http://storage.myapp.com:4569
app.storage.access-key=dev-access-key
app.storage.secret-key=dev-secret-key
app.storage.region=us-east-1
app.storage.bucket=dev-bucket

用法:

./setup.sh dev

由於 (Bourne) shell 變量不能包含點,您可以用下划線替換它們。 閱讀每一行,翻譯。 在關鍵_和評估。

#/bin/sh

file="./app.properties"

if [ -f "$file" ]
then
  echo "$file found."

  while IFS='=' read -r key value
  do
    key=$(echo $key | tr '.' '_')
    eval ${key}=\${value}
  done < "$file"

  echo "User Id       = " ${db_uat_user}
  echo "user password = " ${db_uat_passwd}
else
  echo "$file not found."
fi

請注意,以上僅翻譯 . to _,如果您有更復雜的格式,您可能需要使用其他翻譯。 我最近不得不解析一個包含大量討厭字符的完整 Ant 屬性文件,在那里我不得不使用:

key=$(echo $key | tr .-/ _ | tr -cd 'A-Za-z0-9_')

由於 BASH shell 中的變量名不能包含點或空格,因此最好在 BASH 中使用關聯數組,如下所示:

#!/bin/bash

# declare an associative array
declare -A arr

# read file line by line and populate the array. Field separator is "="
while IFS='=' read -r k v; do
   arr["$k"]="$v"
done < app.properties

測試:

使用 declare -p 顯示結果:

  > declare -p arr  

        declare -A arr='([db.uat.passwd]="secret" [db.uat.user]="saple user" )'

@fork2x

我試過這樣。請檢查並更新我是否正確的方法。

#/bin/sh
function pause(){
   read -p "$*"
}

file="./apptest.properties"


if [ -f "$file" ]
then
    echo "$file found."

dbUser=`sed '/^\#/d' $file | grep 'db.uat.user'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
dbPass=`sed '/^\#/d' $file | grep 'db.uat.passwd'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`

echo database user = $dbUser
echo database pass = $dbPass

else
    echo "$file not found."
fi

我發現使用while IFS='=' read -r有點慢(我不知道為什么,也許有人可以在評論中簡要解釋或指向 SO 答案?)。 我還發現@Nicolai 的回答非常簡潔,但效率很低,因為它會為每次調用prop一遍又一遍地掃描整個屬性文件。

我找到了一個可以回答問題的解決方案,性能很好,而且它是單行的(雖然有點冗長)。

該解決方案進行采購,但在采購之前按摩內容:

#!/usr/bin/env bash

source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')

echo $db_uat_user

解釋:

grep -v '^ *#' :丟棄注釋行grep '[^ ] *=' :丟棄沒有= split($0,a,"=")行:在=處拆分行並存儲到數組a ,即 a[1 ] 是鍵,a[2] 是值gensub(/\\./, "_", "g", a[1]) :替換. with _ print gensub... "=" a[2]}將上面gensub的結果與=和值連接起來。

編輯:正如其他人指出的那樣,存在一些不兼容問題(awk),並且它不會驗證內容以查看屬性文件的每一行是否實際上是一個 kv 對。 但這里的目標是展示一個既快速又干凈的解決方案的總體思路。 采購似乎是一種方法,因為它加載一次可以多次使用的屬性。

對於非常高性能且兼容 BASH 3.0 的解決方案:

文件: loadProps.sh

function loadProperties() {
  local fileName=$1
  local prefixKey=$2

  if [ ! -f "${fileName}" ]; then
    echo "${fileName} not found!"
    return 1
  fi

  while IFS='=' read -r origKey value; do
    local key=${origKey}
    key=${key//[!a-zA-Z0-9_]/_} 
    if [[ "${origKey}" == "#"*   ]]; then
      local ignoreComments
    elif [ -z "${key}" ]; then
      local emptyLine
    else
      if [[ "${prefixKey}${key}" =~ ^[0-9].* ]]; then
        key=_${key}
      fi
      eval ${prefixKey}${key}=\${value}
    fi
  done < <(grep "" ${fileName})
}

這里提供的其他解決方案很棒而且很優雅,但是

  • @fork2execve:處理大型屬性文件時速度很慢
  • @Nicolai:讀取大量屬性時速度很慢
  • @anubhava:需要 BASH 4.0(用於數組)

我需要一些在 bash 3 上工作的東西,處理大約 1k 個條目的屬性文件,讀取大約 200 個屬性,以及多次調用整個腳本。

這個函數也處理

  • 空行
  • 注釋代碼
  • 重復的條目(最后一個獲勝)
  • 規范化屬性名稱
  • 最后一行沒有適當的新行

測試

文件: my.properties

a=value
a=override value
b=what about `!@#$%^&*()_+[]\?
c=${a} no expansion
d=another = (equal sign)
e=     5 spaces front and back     
f=
#g=commented out
#ignore new line below

.@a%^=who named this???
a1=A-ONE
1a=ONE-A
X=lastLine with no new line!

測試腳本

. loadProps.sh

loadProperties my.properties PROP_
echo "a='${PROP_a}'"
echo "b='${PROP_b}'"
echo "c='${PROP_c}'"
echo "d='${PROP_d}'"
echo "e='${PROP_e}'"
echo "f='${PROP_f}'"
echo "g='${PROP_g}'"
echo ".@a%^='${PROP___a__}'"
echo "a1='${PROP_a1}'"
echo "1a='${PROP_1a}'"
echo "X='${PROP_X}'"

loadProperties my.properties
echo "a='${a}'"
echo "1a='${_1a}'"

輸出

a='override value'
b='what about `!@#$%^&*()_+[]\?'
c='${a} no expansion'
d='another = (equal sign)'
e='     5 spaces front and back     '
f=''
g=''
.@a%^='who named this???'
a1='A-ONE'
1a='ONE-A'
X='lastLine with no new line!'
a='override value'
1a='ONE-A'

性能測試

. loadProps.sh

function fork2execve() {
  while IFS='=' read -r key value; do
    key=$(echo $key | tr .-/ _ | tr -cd 'A-Za-z0-9_')
    eval ${key}=\${value}
  done < "$1"
}

function prop {
  grep '^\s*'"$2"'=' "$1" | cut -d'=' -f2-
}

function Nicolai() {
  for i in $(seq 1 $2); do 
    prop0000=$(prop $1 "property_0000")
  done
}

function perfCase() {
  echo "perfCase $1, $2, $3"
  time for i in $(seq 1 1); do 
    eval $1 $2 $3
  done
}

function perf() {
  perfCase $1 0001.properties $2
  perfCase $1 0010.properties $2
  perfCase $1 0100.properties $2
  perfCase $1 1000.properties $2
}

perf "loadProperties"
perf "fork2execve"
perf "Nicolai" 1
perf "Nicolai" 10
perf "Nicolai" 100

帶有 4 個 NNNN.properties 文件,其中包含諸如

property_0000=value_0000
property_0001=value_0001
...
property_NNNN=value_NNNN

導致

function   , file,   #,     real,    user,     sys
loadPropert, 0001,    ,    0.058,   0.002,   0.005
loadPropert, 0010,    ,    0.032,   0.003,   0.005
loadPropert, 0100,    ,    0.041,   0.013,   0.006
loadPropert, 1000,    ,    0.140,   0.106,   0.013

fork2execve, 0001,    ,    0.053,   0.003,   0.007
fork2execve, 0010,    ,    0.211,   0.021,   0.051
fork2execve, 0100,    ,    2.146,   0.214,   0.531
fork2execve, 1000,    ,   21.375,   2.151,   5.312

Nicolai    , 0001,   1,    0.048,   0.003,   0.009
Nicolai    , 0010,   1,    0.047,   0.003,   0.009
Nicolai    , 0100,   1,    0.044,   0.003,   0.010
Nicolai    , 1000,   1,    0.044,   0.004,   0.009

Nicolai    , 0001,  10,    0.240,   0.020,   0.056
Nicolai    , 0010,  10,    0.263,   0.021,   0.059
Nicolai    , 0100,  10,    0.272,   0.023,   0.062
Nicolai    , 1000,  10,    0.295,   0.027,   0.059

Nicolai    , 0001, 100,    2.218,   0.189,   0.528
Nicolai    , 0010, 100,    2.213,   0.193,   0.537
Nicolai    , 0100, 100,    2.247,   0.196,   0.543
Nicolai    , 1000, 100,    2.323,   0.253,   0.534

我認為 Nicolai 的回答很好。 然而,有時人們寫

app.server.address = 127.0.0.70

代替

app.server.address=127.0.0.70

在這種情況下。 如果我們直接使用

function prop {
    grep "${1}" env/${ENV}.properties|cut -d'=' -f2
}

它會產生“127.0.0.70”而不是“127.0.0.70”,在字符串組合中出現一些錯誤。 為了解決這個問題,我們可以添加“| xargs”。 它將是

grep "${1}" ${ENV}.properties|cut -d'=' -f2 | xargs

我們會得到我們想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM