Bash:在遍历二维属性文件时是否有条件子句

问题描述

我有一个由 item [i] 定义的数据结构-包含-> subitem [k] 。我想写一个小的bash脚本来解析子项,然后项在命中特定子项时执行操作。

我的 sampletext.properties 文件是这样的:

Item1.subitem1=tom
Item1.subitem2=bob
Item2.subitem1=alice
Item2.subitem2=cindy

克服了Bash中二维数组的缺失,我编写了两个函数,一个函数用于获取键的值,另一个函数用于计算字符串的出现。

然后我建立一个for循环来解析项目,并尝试包括一个IF子句以敲击“ bob”并说出一些话。不幸的是,该脚本没有看到bob,并且似乎IF子句不起作用:

#!/bin/bash

# The input text file 
PROPERTY_FILE=sampletext.properties

#Defining a function to get the value of a key
function getProperty {
   PROP_KEY=$1
   PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2 | tr -d '\n'`
   echo $PROP_VALUE
}

# Counting the number of subitem1 entries
function countsubitem1 {
  toolsnumber=`cat $PROPERTY_FILE | grep "Item[0-9].subitem1" | wc -l`
  echo $toolsnumber
}
countsubitem1


for (( i=1; i<=$(countsubitem1); i++))
do
  subitem1=`getProperty "Item$i.subitem1"`
  subitem2=`getProperty "Item$i.subitem2"`
  echo item$i:$(getProperty "Item$i.subitem1") # Testing the getProperty function again
  echo subitem2:$subitem2 # Testing the for loop and the getProperty function
  if [[ "$subitem2" == "bob" ]]; then
    echo "I see bob!"
  else
    echo "No bob here!"
  fi  
done

启动脚本的内容:

2
item1:tom
subitem2:bob
No bob here!
item2:alice
subitem2:cindy
No bob here!

我期望的是

./samplebash.sh
2
item1:tom
subitem2:bob
I see bob!
item2:alice
subitem2:cindy
No bob here!

我尝试了几种中频条款的修改:

 if [ "$subitem2" == "bob" ]; then
  if [ '$subitem2' == 'bob' ]; then

但是我总是得到“这里没有鲍勃!”消息。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)