[英]Code for parsing a key/value in in file from shell script
我有一個文件,我需要使用shell腳本按鍵查找值。 該文件看起來像:
HereIsAKey This is the value
我該怎么做:
MyVar=Get HereIsAKey
然后MyVar應該等於“這就是價值”。 密鑰沒有空格,值應該是密鑰后面的空格。
如果HereIsAKey
在您的文件中是唯一的,請使用grep嘗試:
myVar=$(grep -Po "(?<=^HereIsAKey ).*" file)
如果您沒有支持與Perl兼容的正則表達式的grep,則以下似乎有效:
VAR=$(grep "^$KEY " file | cut -d' ' -f2-)
如果您一次只需要一個變量,則可以執行以下操作:
#!/bin/bash
cat file | while read key value; do
echo $key
echo $value
done
此解決方案的問題:變量僅在循環內有效。 所以不要嘗試做$key=$value
並在循環后使用它。
更新:另一種方法是I / O重定向:
exec 3<file
while read -u3 key value; do
eval "$key='$value'"
done
exec 3<&-
echo "$keyInFile1"
echo "$anotherKey"
如果文件未排序,查找將很慢:
my_var=$( awk '/^HereIsAKey/ { $1=""; print $0; exit}' value-file )
如果文件已排序,您可以使用更快的查找
my_var=$( look HereIsAkey value-file | cut -d ' ' -f 2- )
我使用一個跨多種語言共享的屬性文件,我使用了一對函數:
load_properties() {
local aline= var= value=
for file in config.properties; do
[ -f $file ] || continue
while read aline; do
aline=${aline//\#*/}
[[ -z $aline ]] && continue
read var value <<<$aline
[[ -z $var ]] && continue
eval __property_$var=\"$value\"
# You can remove the next line if you don't need them exported to subshells
export __property_$var
done <$file
done
}
get_prop() {
local var=$1 key=$2
eval $var=\"\$__property_$key\"
}
load_properties
從config.properties
文件中讀取,為文件中的每一行填充一組變量__property_...
然后get_prop允許根據加載的屬性設置變量。 它適用於大多數需要的情況。
是的,我確實意識到那里有一個eval,這使得用戶輸入不安全 ,但它適用於我需要它做的事情。
get () {
while read -r key value; do
if [ "$key" = "$1" ]; then
echo "$value"
return 0
fi
done
return 1
}
這兩個返回語句並不是絕對必要的,但提供了很好的退出代碼來指示找到給定鍵的成功或失敗。 它們還可以幫助區分“鍵值為空字符串”和“未找到鍵”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.