使用grep(或类似)在第一次匹配后获取字符串

时间:2014-04-22 04:52:15

标签: regex linux string grep

我们说我在JSON中有一些文字:

{
    "key1": "value1"
    "key2": "value2"
    "key3": "value3"
    "key4": "value4"
    "key5": "value5"
}
{
    "key1": "value1"
    "key2": "value2"
    "key3": "value3"
    "key4": "value4"
    "key5": "value5"
}

我想要做的是找到" value1",但只打印" value5"。会有很多" value5"(s),但我只想打印它,如果前面是" value1" (这将是一个独特的字符串)。我无法使用grep -Ax & -Bx

由于我不想在之后匹配该行,而是想要打印该字符串。

1 个答案:

答案 0 :(得分:0)

示例文件:

cat t
{
    "key1": "value1"
    "key2": "value2"
    "key3": "value3"
    "key4": "value4"
    "key5": "value5"
}
{
    "key1": "value6"
    "key2": "value2"
    "key3": "value3"
    "key4": "value4"
    "key5": "value5"
}

如果key5

,请在key1=value6打印数据
awk '/key1/ && /value6/ {f=1} f && /key5/ {print $NF;f=0}'
"value5"