0

I execute the following command:

xinput  | grep Razer

the output is

⎜   ↳ Razer  Razer Abyssus                      id=12   [slave  pointer  (2)]

how can I get the id, assign it to a variable, so I can reuse it later in the script? The id is changing.

3 Answers 3

2

You can pipe your command to sed:

yourvar=$(xinput | sed '/Razer/s/.*id=\([0-9]*\).*/\1/')
  • /Razer/: when a line containing Razer is found
  • s/.*id=\([0-9]*\).*/\1/: capture the id value and print it using backreference.
Sign up to request clarification or add additional context in comments.

1 Comment

Hi. I tried it... yourvar=$(xinput | sed '/Touchpad/s/.*id=([0-9]*).*/\1/') but when echoing $yourvar, the the whole result of xinput is given, and not just the number following the "id=" sub-string. I do have the following line in my xinput readout: ⎜ ↳ ELAN0518:01 04F3:31FC Touchpad id=11 [slave pointer (2)] I'm using bash 5.1.16 Any advice?
1

grep solution: Here if any line contains Razer followed by id then the ID is printed. Here perl regex is used by using -p flag of grep command. \K means ignore everything on left of it.

xinput  |grep -oP 'Razer.*id=\K[^ ]+'
12

Using gawk's match function:

awk '/Razer/{match($0,/id=([^ ]+)/,a);print a[1]}'
12

Comments

0

if you've GNU AWK or gawk you can do the below too.

id=$(xinput | awk '/Razer/{printf "%s",gensub(/^.*id=[[:digit:]]*).*$/,"\\1",$0)}')

2 Comments

Hi do you want to change your regex to /^.*id=([[:digit:]]*).*$/ ?
@PS : You're right, It so happened that the = got trimmed when I copied the command from my VM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.