Bash 解析动态数组并将特定值存储在另一个

Bash parse dynamic arrays and store specific values in an other

我正在发送一个 dbus-send 命令,它 returns 类似于:

method return sender=:1.833 -> dest=:1.840 reply_serial=2
   array of bytes [
      00 01 02 03 04 05 
   ]
   int 1
   boolean true

"array of bytes" 大小是动态的,可以包含 n 个值。

我使用以下方法将 dbus-send 命令的结果存储在一个数组中:

array=($(dbus-send --session --print-repl ..readValue))

我希望能够检索包含在字节数组中的值,并能够在必要时显示其中一个或所有值,如下所示:

data read => 00 01 02 03 04 05
or 
first data read => 00

{array[10]} 始终可以访问第一个数据,我认为是否可以使用像这样的结构:

IFS=" " read -a array 
for element in "${array[@]:10}"
do
    ...
done

对如何实现这个有任何想法吗?

你真的应该为 dbus 使用一些库,比如 Net::DBus 或类似的东西。

无论如何,对于上面的例子你可以这样写:

#fake dbus-send command
dbus-send() {
    cat <<EOF
method return sender=:1.833 -> dest=:1.840 reply_serial=2
   array of bytes [
      00 01 02 03 04 05 
   ]
   int 1
   boolean true
EOF
}

array=($(dbus-send --session --print-repl ..readValue))

data=($(echo "${array[@]}" | grep -oP 'array\s*of\s*bytes\s*\[\s*\K[^]]*(?=\])'))

echo "ALL data ==${data[@]}=="
echo "First item: ${data[0]}"
echo "All items as lines"
printf "%s\n" "${data[@]}"

data=($(echo "${array[@]}" | sed 's/.*array of bytes \[\([^]]*\)\].*//'))

echo "ALL data ==${data[@]}=="
echo "First item: ${data[0]}"
echo "All items as lines"
printf "%s\n" "${data[@]}"

对于两个示例打印

ALL data ==00 01 02 03 04 05==
First item: 00
All items as lines
00
01
02
03
04
05