Ubuntu – How to concatenate two command in shell

bashcommand linedash-shellscripts

I used to have this command to count how many times I have click with a mouse, the command is xev | grep "ButtonPress".

my colleague modify the command so that it return:

ButtonPress 0
ButtonPress 1
ButtonPress 2
ButtonPress 3

and so on… Unfortunately he's no longer contactable so I can't reach him anymore.

I recall the involvement of i++ and something like that, how to reproduce the command?

Best Answer

The fact that there's i++ suggests there was either bash or ksh shell in use,potentially awk or perl as well. In either case, we can use process substitution <(...) to feed output of xev to counting loop (although simple pipeline xev | while... could work just fine).

text processing tools:

Portably and for fewer key strokes we can use awk :

$ xev | awk '/ButtonPress/{print "ButtonPress",i++}'
ButtonPress 0
ButtonPress 1
ButtonPress 2
ButtonPress 3

perl version:

$ xev | perl -ne '/ButtonPress/ && printf("ButtonPress:%d\n",++$i)'
ButtonPress:1
ButtonPress:2
ButtonPress:3

Shells:

Here's what works in bash:

$ i=0; while IFS= read -r line; do [[ $line =~ ButtonPress ]] && { ((i++)); printf 'ButtonPress: %d\n' "$i";} ;done < <(xev)
ButtonPress: 1
ButtonPress: 2
ButtonPress: 3

In case you don't want spammy output of many lines, we can use printf to send control code to clear previous line and output only the running count (that is you'd only see integer value change on the line):

$ i=0; while IFS= read -r line; do [[ $line =~ ButtonPress ]] && { ((i++)); printf "\r%b" "\033[2K"; printf 'ButtonPress: %d' "$i";} ;done < <(xev)

Portably in POSIX shell:

$ xev | ( i=0; while IFS= read -r l; do case "$l" in  *ButtonPress*) i=$((i+1)) && printf 'ButtonPress:%d\n' "$i";;  esac ;done)
ButtonPress:1
ButtonPress:2
ButtonPress:3

basic utils:

For simple, quick, and dirty way we can hack this via cat -n with line count being printed on the left instead of right:

$ xev | grep --line-buffered 'ButtonPress' | cat -n
     1  ButtonPress event, serial 34, synthetic NO, window 0x4a00001,
     2  ButtonPress event, serial 34, synthetic NO, window 0x4a00001,
     3  ButtonPress event, serial 34, synthetic NO, window 0x4a00001,
Related Question