I'm using grep on Ubuntu Desktop 20.04.
I want to get player movements from gnuchess game by using grep each turn. The first command i used is this :
gnuchess -mq | grep -a "Black ([0-9][0-9]*) : [0-9][0-9]*. [a-z][0-9]" | grep "[a-z][0-9]"
for the first grep, if movements are 'e3' and 'e5', the output is :
Black (1) : 1. e5
I expect the second grep give me e5 but it doesn't. Output is blank.
Yet when i redirect gnuchess output to a file and use the same command it works and shows e5. Why?
Edit:
The problem was with output buffering. Added my answer below.
turning off output buffering did the work.
gnuchess -mq | stdbuf -o0 grep -a "Black ([0-9][0-9]*) : [0-9][0-9]*. [a-z][0-9]" | grep -o "[a-z][0-9]"
For more information: this
grep
returns the whole line where it finds a match, so the behaviour you experience is the expected one.If you are sure that what you want is the fifth token of the string, you can use
awk
:For example:
echo 'Black (1) : 1. e5' | grep -a "Black ([0-9][0-9]*) : [0-9][0-9]*. [a-z][0-9]" | awk '{print $5}'
returns onlye5
.