Reputation: 93
My code is like this:
xinput list | grep TouchPad
then I get:
SynPS/2 Synaptics TouchPad id=14 [slave pointer
(2)]
I save this output to a string variable in this way:
touchpad=$(xinput list | grep TouchPad)
So, my question is, how can I save the ID number 14 as into a number variable in the bash script? I need to use that number to turn off the TouchPad by this:
xinput set-prop 14 "Device Enabled" 0
I need to run the code automatically, so the number 14 in the above code should come from the previous code.
Thanks.
Upvotes: 0
Views: 1567
Reputation: 22438
Using Bash Parameter Expansion:
var='SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]'
num="${var/*TouchPad id=/}" # replaces ...TouchPad id= with empty string
num="${num/ */}" # replaces space... with empty string
echo "$num"
Or
num="${var#*TouchPad id=}" # deletes ...TouchPad id= from var and assigns the remaining to num
num="${num%% *}" # deletes space... from num
Or using grep with Perl regex:
echo "$var" |grep -oP "(?<=TouchPad id=)\d+"
Upvotes: 0
Reputation: 14198
In your bash script:
regex="id=([0-9]+)"
[[ $touchpad =~ $regex ]]
id=${BASH_REMATCH[1]}
if [ -z $id ]; then
echo "Couldn't parse id for $touchpad"
else
xinput set-prop $id "Device Enabled" 0
fi
Upvotes: 0
Reputation: 53565
num=$(echo " SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]" | grep -o '\d\d')
echo $num
OUTPUT
14
Upvotes: 1
Reputation: 5315
touchpad='SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]'
sed -r 's~.*TouchPad id=([0-9]+).*~\1~' <<< "$touchpad"
14
Upvotes: 0