Kil*_*sh9 20 variables bash awk parsing
在文件中包含以下内容:
VARIABLE1="Value1"
VARIABLE2="Value2"
VARIABLE3="Value3"
Run Code Online (Sandbox Code Playgroud)
我需要一个输出以下内容的脚本:
Content of VARIABLE1 is Value1
Content of VARIABLE2 is Value2
Content of VARIABLE3 is Value3
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
gle*_*man 59
由于您的配置文件是有效的shell脚本,因此您可以将其源代码发送到当前的shell:
. config_file
echo "Content of VARIABLE1 is $VARIABLE1"
echo "Content of VARIABLE2 is $VARIABLE2"
echo "Content of VARIABLE3 is $VARIABLE3"
Run Code Online (Sandbox Code Playgroud)
稍微干,但比较棘手
. config_file
for var in VARIABLE1 VARIABLE2 VARIABLE3; do
echo "Content of $var is ${!var}"
done
Run Code Online (Sandbox Code Playgroud)
ant*_*nio 35
如果你需要这些......
=(即var = value不会失败);shopt -s extglob
configfile="dos_or_unix" # set the actual path name of your (DOS or Unix) config file
tr -d '\r' < $configfile > $configfile.unix
while IFS='= ' read -r lhs rhs
do
if [[ ! $lhs =~ ^\ *# && -n $lhs ]]; then
rhs="${rhs%%\#*}" # Del in line right comments
rhs="${rhs%%*( )}" # Del trailing spaces
rhs="${rhs%\"*}" # Del opening string quotes
rhs="${rhs#\"*}" # Del closing string quotes
declare $lhs="$rhs"
fi
done < $configfile.unix
Run Code Online (Sandbox Code Playgroud)
tr -d '\r' ...删除DOS回车.
! $lhs =~ ^\ *#跳过单行注释并-n $lhs跳过空行.
删除尾随空格${rhs%%*( )}需要设置扩展的globbing shopt -s extglob.(除了使用sed),您可以通过更复杂的方式避免这种情况:
rhs="${rhs%"${rhs##*[^ ]}"}"
Run Code Online (Sandbox Code Playgroud)
## This is a comment
var1=value1 # Right side comment
var2 = value2 # Assignment with spaces
## You can use blank lines
var3= Unquoted String # Outer spaces trimmed
var4= "My name is " # Quote to avoid trimming
var5= "\"Bob\""
Run Code Online (Sandbox Code Playgroud)
echo "Content of var1 is $var1"
echo "Content of var2 is $var2"
echo "Content of var3 is [$var3]"
echo "Content of var4 + var5 is: [$var4$var5]"
Run Code Online (Sandbox Code Playgroud)
Content of var1 is value1
Content of var2 is value2
Content of var3 is [Unquoted String]
Content of var4 + var5 is: [My name is "Bob"]
Run Code Online (Sandbox Code Playgroud)
aba*_*asu 32
awk -F\= '{gsub(/"/,"",$2);print "Content of " $1 " is " $2}' <filename>
仅供参考,另一种纯粹的bash解决方案
IFS="="
while read -r name value
do
echo "Content of $name is ${value//\"/}"
done < filename
Run Code Online (Sandbox Code Playgroud)
我是这样做的
. $PATH_TO_FILE
Run Code Online (Sandbox Code Playgroud)