Using grep to match only a match group in a regular expression

grepregular expression

I need to set my keyboard layout with setxkbmap before launching Wine games, as I use Dvorak for typing and this breaks every game's controls. What I'd like to do is simply write a script that grabs the current keyboard layout before starting the game, stores it in a variable, then restores it after the game is done:

ORIGINAL_LAYOUT=`setxkbmap -query | grep -P 'layout\:\s{5}(\w+)'`
setxkbmap us
wine ...
setxkbmap $ORIGINAL_LAYOUT

The problem that I'm having is that grep matches the entire line and not just my capture group. Is there a way for me to simply dump the matched capture group?

For example, the output of setxkbmap -query is:

rules:      evdev
model:      pc105
layout:     dvorak

I'm interested in grabbing the layout.

Best Answer

Try using this awk command:

setxkbmap -query | grep layout | awk '{print $2}'

or use cut command

setxkbmap -query | grep layout | cut -d : -f2

Related Question