Can not extract the capture group with neither sed nor grep

后端 未结 5 1654
猫巷女王i
猫巷女王i 2021-01-30 08:16

I want to extract the value pair from a key-value pair syntax but I can not.
Example I tried:

echo employee_id=1234 | sed \'s/employee_id=\\([0-9]+\\)/\\1/         


        
相关标签:
5条回答
  • 2021-01-30 08:53

    Using awk

    echo 'employee_id=1234' | awk -F= '{print $2}'
    1234
    
    0 讨论(0)
  • 2021-01-30 08:56

    1. Use grep -Eo: (as egrep is deprecated)

    echo 'employee_id=1234' | grep -Eo '[0-9]+'
    
    1234
    

    2. using grep -oP (PCRE):

    echo 'employee_id=1234' | grep -oP 'employee_id=\K([0-9]+)'
    
    1234
    

    3. Using sed:

    echo 'employee_id=1234' | sed 's/^.*employee_id=\([0-9][0-9]*\).*$/\1/'
    
    1234
    
    0 讨论(0)
  • 2021-01-30 09:00

    To expand on anubhava's answer number 2, the general pattern to have grep return only the capture group is:

    $ regex="$precedes_regex\K($capture_regex)(?=$follows_regex)"
    $ echo $some_string | grep -oP "$regex"
    

    so

    # matches and returns b
    $ echo "abc" | grep -oP "a\K(b)(?=c)" 
    b 
    # no match
    $ echo "abc" | grep -oP "z\K(b)(?=c)"
    # no match
    $ echo "abc" | grep -oP "a\K(b)(?=d)"
    
    0 讨论(0)
  • 2021-01-30 09:15

    You are specifically asking for sed, but in case you may use something else - any POSIX-compliant shell can do parameter expansion which doesn't require a fork/subshell:

    foo='employee_id=1234'
    var=${foo%%=*}
    value=${foo#*=}
    

     

    $ echo "var=${var} value=${value}"
    var=employee_id value=1234
    
    0 讨论(0)
  • 2021-01-30 09:19

    use sed -E for extended regex

        echo employee_id=1234 | sed -E 's/employee_id=([0-9]+)/\1/g'
    
    0 讨论(0)
提交回复
热议问题