解析出这些值很容易,一旦你有了它们,你当然可以使用这些值来构建一个数组。最棘手的部分来自您需要组合来自不同行的输入这一事实。这是一种方法;请注意,此脚本是故意冗长的,以显示正在发生的事情;一旦你看到发生了什么,你就可以消除大部分输出:
so.input
"HardwareSerialNumber": "123456789101",
"DeviceId": "devid1234",
"HardwareSerialNumber": "111213141516",
"DeviceId": "devid5678",
so.sh
#!/bin/bash
declare -a hardwareInfo
while [[ 1 ]]; do
# read in two lines of input
# if either line is the last one, we don't have enough input to proceed
read lineA < "${1:-/dev/stdin}"
# if EOF or empty line, exit
if [[ "$lineA" == "" ]]; then break; fi
read lineB < "${1:-/dev/stdin}"
# if EOF or empty line, exit
if [[ "$lineB" == "" ]]; then break; fi
echo "$lineA"
echo "$lineB"
hwsn=$lineA
hwsn=${hwsn//HardwareSerialNumber/}
hwsn=${hwsn//\"/}
hwsn=${hwsn//:/}
hwsn=${hwsn//,/}
echo $hwsn
# some checking could be done here to test that the value is numeric
devid=$lineB
devid=${devid//DeviceId/}
devid=${devid//\"/}
devid=${devid//:/}
devid=${devid//,/}
echo $devid
# some checking could be done here to make sure the value is valid
# populate the array
hardwareInfo[$hwsn]=$devid
done
# spacer, for readability of the output
echo
# display the array; in your script, you would do something different and useful
for key in "${!hardwareInfo[@]}"; do echo $key --- ${hardwareInfo[$key]}; done
cat so.input | ./so.sh
"HardwareSerialNumber": "123456789101",
"DeviceId": "devid1234",
123456789101
devid1234
"HardwareSerialNumber": "111213141516",
"DeviceId": "devid5678",
111213141516
devid5678
111213141516 --- devid5678
123456789101 --- devid1234
我创建输入文件so.input 只是为了方便。您可能会将您的 grep 输出通过管道传输到 bash 脚本中,如下所示:
grep-command | ./so.sh
编辑#1:有很多选择可以从grep 输入的字符串中解析出键和值; @David C. Rankin 的回答显示了另一种方式。最好的方法取决于您可以依赖 grep 输出的内容和结构。
也有几种选择可以读取相互关联的两条单独的行; David 的“切换”方式也不错,常用;我自己考虑过,然后再使用“读取两行并在其中一个为空白时停止”。
编辑#2:我在大卫的回答和网络上的示例中看到了declare -A;我使用了declare -a,因为这是我的bash 版本想要的(我使用的是Mac)。因此,请注意可能存在差异。