zhoudingjiang
zhoudingjiang

Reputation: 93

extract numbers from string in bash script

My code is like this:

then I get:

I save this output to a string variable in this way:

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:

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

Answers (4)

Jahid
Jahid

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

Dave
Dave

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

Nir Alfasi
Nir Alfasi

Reputation: 53565

num=$(echo " SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]" | grep -o '\d\d')
echo $num

OUTPUT

14

Upvotes: 1

Eugeniu Rosca
Eugeniu Rosca

Reputation: 5315

touchpad='SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]'
sed -r 's~.*TouchPad id=([0-9]+).*~\1~' <<< "$touchpad"
14

Upvotes: 0

Related Questions