我正在尝试grep的实时文本流netcat,但是对我来说不起作用:
netcat localhost 9090 | grep sender
什么也不会返回,但是我确定应该会返回。
如果我将netcat输出重定向到文件并添加一些延迟(模拟真实环境),则它可以工作:
$ (sleep 5; cat netcat_output; sleep 5) | grep sender
{"jsonrpc":"2.0","method":"GUI.OnScreensaverDeactivated","params":{"data": "shuttingdown":false},"sender":"xbmc"}}
我也尝试添加--line-buffered但没有成功。
我做错了什么?
编辑:
我注意到与相同的问题sed,输出为空。
但是,例如,hexdump将文本实时转换为十六进制:
$ netcat localhost 9090 | hexdump -C
00000000  7b 22 6a 73 6f 6e 72 70  63 22 3a 22 32 2e 30 22  |{"jsonrpc":"2.0"|
00000010  2c 22 6d 65 74 68 6f 64  22 3a 22 50 6c 61 79 65  |,"method":"Playe|
00000020  72 2e 4f 6e 50 6c 61 79  22 2c 22 70 61 72 61 6d  |r.OnPlay","param|
00000030  73 22 3a 7b 22 64 61 74  61 22 3a 7b 22 69 74 65  |s":{"data":{"ite|
00000040  6d 22 3a 7b 22 69 64 22  3a 36 2c 22 74 79 70 65  |m":{"id":6,"type|
00000050  22 3a 22 6d 6f 76 69 65  22 7d 2c 22 70 6c 61 79  |":"movie"},"play|
00000060  65 72 22 3a 7b 22 70 6c  61 79 65 72 69 64 22 3a  |er":{"playerid":|
00000070  31 2c 22 73 70 65 65 64  22 3a 31 7d 7d 2c 22 73  |1,"speed":1}},"s|
                  这样工作吗?
                
                  
                    —
                    Gilles Quenot 2014年
                    
                  
                
              netcat -z localhost 9090 | grep sender
                
                  @ user43791输出仍然为空,但是我确定netcat返回了匹配的字符串
                
                
                  
                    —
                    tomekceszke 2014年
                    
                  
                
              
                  @sputnick,此人立即返回外壳,不等待事件发生
                
                
                  
                    —
                    tomekceszke 2014年
                    
                  
                
              
                  hexdump中没有新行,因此
                
                  
                    —
                    muru 2014年
                    
                  
                
              grep可能无休止地在等待新行。cat工程自grep会得到一个EOF如果不换行,至少。也许尝试awk与{作为RS?
                
stdbuf -o0 netcat localhost 9090 | grep sender(取自此处)