Search code examples
bashsedgrep

Using grep or sed to extract the numerical value of the 'device id' in bash


A line from xinput says ⎜ ↳ ELAN0518:01 04F3:31FC Touchpad id=11 [slave pointer (2)] I want to grab the number immediately following the "id=" part into a variable.

The proposed solution posted 6 years ago here: substring with bash and assign to a variable doesn't work and another proposed solution...

yourvar=$(xinput  |grep -oP 'Touchpad.*id=\K[^ ]+')
echo $yourvar

almost works but leaves trailing string, outputting: "11 [slave"

How to adjust the grep command to just grab the number?


Solution

  • You are using [^ ]+ which matches not a space. If there is for example a tab, you will match too much.

    You might use for example \S+ to match 1+ non whitespace chars:

    Touchpad.*id=\K\S+
    

    Or match 1 or more digits to a more precise pattern:

    Touchpad.*id=\K\d+