bash - using head -n1 to get first match of grep on osx -


i trying use head -n1 first grep match (which suggested few places)

i expect work

$ printf "x=0;\nwhile true:\n x+=1\n print x" | python | grep -w 333 | head -n1 

(pipe goes on forever grep command select single line, , take first line output)

however, there no output, , never stops.

this works expected: (take first line of infinite output, without grep)

$ printf "x=0;\nwhile true:\n x+=1\n print x" | python | head -n1 1 traceback (most recent call last):   file "<stdin>", line 4, in <module> ioerror: [errno 32] broken pipe 

and works: (grep output , single match)

$ printf "x=0;\nwhile true:\n x+=1\n print x" | python | grep -w 333 333 

(and never exits)

however, combination doesn't give me expect:

$ printf "x=0;\nwhile true:\n x+=1\n print x" | python | grep -w 333 | head -n1 

(never prints , never exits)

you need use --line-buffered option in grep:

printf "x=0;\nwhile true:\n x+=1\n print x" | python | grep --line-buffered -w 333 | head -n 1 333 

as per man grep:

--line-buffered      force output line buffered.  default, output line buffered when standard      output terminal , block buffered otherwise. 

however note command won't exit since running infinite loop in python code.

if want pipeline exit after printing first match use awk:

printf "x=0;\nwhile true:\n x+=1\n print x" | python |& awk '$1=="333"/{print; exit}' 333 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -