shell:从具有已知密钥的字符串中提取键值

时间:2015-10-27 12:35:01

标签: linux bash shell sed grep

我有一个脚本,其中运行以下命令:

OUTPUT=`echo "User-Name=$username,User-Password=$passwd" | radclient $ip auth $key`
echo $OUTPUT

执行命令后,我在OUTPUT中得到以下结果。

Received response ID 239, code 2, length = 34
        Reply-Message = "Hello, root"

然后我会检查OUPUT是否包含"代码"

if grep -wq code <<< $OUTPUT; then    
    echo "Success"
    break;
fi

这也有效。

现在,如果我的OUTPUT变量包含代码,那么我想提取代码值: 2 (在上面的例子中)

如何实现这一目标:

所以输入:

Received response ID 239, code 2, length = 34
            Reply-Message = "Hello, root"

输出: 2

3 个答案:

答案 0 :(得分:2)

laravel 5

答案 1 :(得分:0)

echo "${OUTPUT}" | sed -e '/.*, code \([^,]\{1,\}\).*/ !d' -e 's//\1/'

posix兼容,因此将适用于任何最近的sed

答案 2 :(得分:0)

你可以直接在bash中进行,它有正则表达式支持,在你的情况下它可以是这样的:

read A < <(echo 'Received response ID 239, code 2, length = 34')
if [[ "$A" =~ ^Received\ response\ ID\ [0-9]+,\ code\ ([0-9]+),\ length\ =\ ([0-9]+) ]]; then echo ${BASH_REMATCH[1]} - ${BASH_REMATCH[2]}; else echo nope; fi