从 bash 脚本中的字符串中提取数字
extract numbers from string in bash script
我的代码是这样的:
xinput list | grep TouchPad
然后我得到:
- ├ ↳
SynPS/2 Synaptics TouchPad id=14 [slave pointer
(2)]
我以这种方式将此输出保存到字符串变量中:
touchpad=$(xinput list | grep TouchPad)
所以,我的问题是,如何将 ID 号 14 保存到 bash 脚本中的数字变量中?我需要使用这个数字来关闭触摸板:
xinput set-prop 14 "Device Enabled" 0
我需要自动运行代码,所以上面代码中的数字14应该来自前面的代码。
谢谢。
touchpad='SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]'
sed -r 's~.*TouchPad id=([0-9]+).*~~' <<< "$touchpad"
14
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+"
num=$(echo " SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]" | grep -o '\d\d')
echo $num
输出
14
在您的 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
我的代码是这样的:
xinput list | grep TouchPad
然后我得到:
- ├ ↳
SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]
我以这种方式将此输出保存到字符串变量中:
touchpad=$(xinput list | grep TouchPad)
所以,我的问题是,如何将 ID 号 14 保存到 bash 脚本中的数字变量中?我需要使用这个数字来关闭触摸板:
xinput set-prop 14 "Device Enabled" 0
我需要自动运行代码,所以上面代码中的数字14应该来自前面的代码。
谢谢。
touchpad='SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]'
sed -r 's~.*TouchPad id=([0-9]+).*~~' <<< "$touchpad"
14
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+"
num=$(echo " SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]" | grep -o '\d\d')
echo $num
输出
14
在您的 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