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.
答案 0 :(得分:1)
num=$(echo " SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]" | grep -o '\d\d')
echo $num
<强>输出强>
14
答案 1 :(得分:0)
$_
答案 2 :(得分:0)
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"
或
num="${var#*TouchPad id=}" # deletes ...TouchPad id= from var and assigns the remaining to num
num="${num%% *}" # deletes space... from num
或者将grep与Perl正则表达式一起使用:
echo "$var" |grep -oP "(?<=TouchPad id=)\d+"
答案 3 :(得分:0)
在你的bash脚本中:
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