Search code examples
regexmacossedmacos-high-sierra

using sed to find a value given a regex


I am trying to get a value from some output. Let's say I want the id property of this json object:

{"id":123,"useless1":"uselessValue","useless2":uselessValue}

I tried this:

a={"id":123,"useless1":"uselessValue","useless2":uselessValue}
echo $a | sed -e s/.*"id":(\d+).*/$1/g

But it returns {"id":123,"useless1":"uselessValue","useless2":uselessValue}

I also tried this example

If I copy:

echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'

I get:

12 BBQ ,45 rofl, 89 lol

Instead of 45

I am using MacOs High Sierra (10.13.6)


Solution

  • If you use jq, it will be as easy as

    jq '.id' file
    

    If you want to fix your sed command, make sure to use BRE POSIX compliant pattern and \1 placeholder in the RHS:

    sed -e 's/.*"id":\([0-9][0-9]*\).*/\1/'
    

    POIs:

    • Capturing groups are defined with \(...\)
    • One or more digits are matched with [0-9][0-9]*