grep 的输出在保存到数组时会被冒号分割

问题描述 投票:0回答:1

我有一个包含数组的文件,看起来像

{
    [commandA]: cmdA,
    [commandB]: cmdB,
...
}

我想通过 grep 命令获取行并将它们存储在 bash 数组中。但当我这么做的时候

cmdFunMap=(`grep "^    \[command" myfile`)
printf '%s\n' "${cmdFunMap[@]}"

我明白了

[commandA]:
cmdA,
[commandB]:
cmdB,

而不是需要的

[commandA]: cmdA,
[commandB]: cmdB,

我尝试像这样匹配整行

cmdFunMap=(`grep "^    \[command.*$" myfile`)
printf '%s\n' "${cmdFunMap[@]}"

并将 IFS 设置为 ,但结果是一样的。

Bash v5.0.17(1)-release (x86_64-pc-linux-gnu)、Ubuntu 20.04.3 LTS (WSL)。

如何修复冒号分离问题?

更新:检查了Alpine 3.15.4,行为是一样的。

bash grep windows-subsystem-for-linux wsl-2 text-parsing
1个回答
0
投票

好吧,伙计,让我们来解决这个结肠难题。看来您的 grep 输出在欺骗您,我们需要将其调整好。这是给你的修复:

# Use grep with the -o option to print only the matched part of the line
# We'll also match the part after the colon to get the full command
cmdFunMap=(`grep -o "^    \[command[^:]*: [^,]*" myfile`)
printf '%s\n' "${cmdFunMap[@]}"

这应该会给你你想要的输出:

[commandA]: cmdA,
[commandB]: cmdB,

这就是使用 -o 选项来获取您需要的部分。祝你的 bash 数组好运,不要让那些棘手的冒号打败你!如果您遇到更多障碍,请记住,我们澳大利亚人习惯于与有点难以预测的生物打交道,例如袋鼠和熊。干杯!

© www.soinside.com 2019 - 2024. All rights reserved.