Tutorial :Shell Script - How to get stuff between two separators


I've got something like that:

xinput --list  ⎡ Virtual core pointer                      id=2    [master pointer  (3)]  ⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]  ⎜   ↳ Microsoft Basic Optical Mouse             id=8    [slave  pointer  (2)]  ⎣ Virtual core keyboard                     id=3    [master keyboard (2)]      ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]      ↳ Power Button                              id=6    [slave  keyboard (3)]      ↳ Power Button                              id=7    [slave  keyboard (3)]      ↳ CHICONY HP Basic USB Keyboard             id=9    [slave  keyboard (3)]  

And I want to get the id number. I've try something like awk -F 'id=' '[print $2} but text after the id number is still here! How i can only get the id number!

Thanks in advance.


This may not be the shortest, but should be easy to understand for anyone with a little bit of awk knowledge:

awk '{ for (i = 1; i <= NF; i++) if ($i ~ /id=/) { print substr($i, 4); break; } }'  



xinput --list | grep -Eo 'id=[0-9]+' | grep -Eo '[0-9]+'  


xinput --list | grep -Eo 'id=[0-9]+' | awk -F= '{print $2}'  


one way

xinput --list | awk -F"id=" 'NF{split($2,a," ");print a[1]}' file  

with the shell(bash)

#!/bin/bash  xinput --list | while read -r line  do    case "$line" in     *id=* )       line=${line##*id=}       echo ${line%% *}    esac  done  


try something like this:

xinput --list | while read line; do      ID=`echo ${line} | cut -d= -f2 | cut -d\[ -f1 | xargs`      echo ${ID}  done  


Bash only:

while read line ; do      if [[ $line =~ id=([[:digit:]]) ]] ; then          echo "${BASH_REMATCH[1]}"      fi  done < <( xinput --list )  


I find these things simplest with sed, using substitution of a group to capture the data you want and ensuring the rest of the line is matched in the regex.

sed 's/.*id=\([0-9]*\).*/\1/'  



cat x | awk -Fid= '{print $2}' | awk  '{print $1}'  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »