3

I'm trying to use grep to get a regex result and pipe the results on-the-fly to telnet running an open port to a node server.

The grep received continuous, but varied in interval, commands from a program running, greps out a number then pipes that over telnet. Heres my example attempt:

echo "TEST 1234\r\n" | grep -e "[0-9]{4}" | telnet 127.0.0.1 1234

I can't change the string format of the echo "spoof". The echo without the grep does successfully send the string to telnet. The grep doesn't seem to be sending to stdOut.

I'm expecting telnet to receive data from the pipe like:

1234
7645
8376

Any help to how to achieve this?

kirgy
  • 179
  • 10

3 Answers3

3

I'm not sure how you reached the conclusion that grep does not print its output on stdout, that's just incorrect.

I would suggest that you test this by adding one step of the pipeline at a time to see where the problems occur.
You'll first find that your echo command literally prints \r\n at the end (you may want echo -e) and that your grep command doesn't print anything (because your pattern doesn't actually match).

However, if you fix the pattern (either grep -e "[0-9]\{4\}" or grep -E "[0-9]{4}") you'll note that it prints the whole line for all lines that match, not just the matching part (you may want grep -o).

Something like this seems like a more reasonable beginning of your pipeline:

 echo -e "TEST 1234\r\n" | grep -o -e "[0-9]\{4\}" 

You should be able to continue from there (however, I would suggest considering using nc instead of telnet).

Håkan Lindqvist
  • 33,741
  • 5
  • 65
  • 90
0

You have to change grep to:

grep -e "[0-9]\{4\}"
0

You don't need telnet to achieve that, Bash shell has this feature builtin, for example:

exec {stream}<>/dev/tcp/127.0.0.1/1234
printf "TEST 1234\r\n" >&${stream}
grep -o "[0-9]\{4\}" <&${stream}
kenorb
  • 5,943
  • 1
  • 44
  • 53