1

So, here I have a simple commmand:

xset -q | grep -e Num -e Caps

The output of the command is:

00: Caps Lock:   off    01: Num Lock:    on     02: Scroll Lock: off

What I want to know is that, are there any possibilities of printing only the on and off parts, such as,

  • print only off after Caps Lock
  • print only on after Num Lock

E.g., if I need to get the status of Caps Lock, I need to run the command such that the output is only

off or on

2
  • What's the output you're looking for? Given an example.
    – muru
    Nov 29, 2015 at 6:32
  • @muru - added the example
    – Raphael
    Nov 29, 2015 at 6:35

2 Answers 2

2

Using grep:

% xset -q | grep -Eo '(Caps Lock|Num Lock):[[:blank:]]+[^[:blank:]]+'
Caps Lock:   off
Num Lock:    on
  • (Caps Lock|Num Lock) matches either Caps Lock or Num Lock

  • the above will be followed by : and then character class [[:blank:]] matches one or more space or tab

  • Them [^[:blank:]]+ will match one or more characters prior to next space or tab i.e. on or off.

2
  • @heemyl - thank you so much! That worked as expected but could you please explain the command a little as I am a newbie here, I shall be greatly obliged.
    – Raphael
    Nov 29, 2015 at 6:38
  • @Raphael Please check my edits
    – heemayl
    Nov 29, 2015 at 6:42
2

You can use AWK as well. It allows printing columns (which are by default assumed to be space separated)

xieerqi:$ xset -q | awk '/Caps/'                                                                      
    00: Caps Lock:   off    01: Num Lock:    off    02: Scroll Lock: off
xieerqi:$ xset -q | awk '/Caps Lock/ {print $4" "$8}'                                                 
off off
7
  • What does {print $4" "$8} do?
    – Raphael
    Nov 29, 2015 at 6:50
  • @Raphael it tells awk to print column 4 and column 8. The " " tells to just put space in between Nov 29, 2015 at 6:51
  • note the space is the default separator, so saying print $1 " " $2 is exactly the same as print $1, $2.
    – fedorqui
    Nov 29, 2015 at 12:07
  • @fedorqui thank you , noted. Is this a gawk specific feature or it is not limited to that ? Also, where in the man page can be found info on this ? Nov 29, 2015 at 12:23
  • It is common in all awks. Check OFS in any man, for example manpagez.com/man/1/awk --> `OFS output field separator (default blank).
    – fedorqui
    Nov 29, 2015 at 12:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .