0

How would I print the nth line of a file or input, and block until it exists? I want to stick to coreutils.

sed 'NUMq;d' file will quickly give me the nth line, but doesn't block.

tail -f file will block, but doesn't do the other thing.

I should be able to pipe the line to something else eg with a file:

<block-until-line-20-exists> file | <process-line>

or, with input:

tail -n 0 -f file | <block-until-line-20-exists> | <process-line>

2
  • Re: tail -n 0 -f file | block-until-line-20-exists, think about { while (( i=0; i<20; i++)); do IFS= read -r line; done; printf '%s\n' "$line"; } as something that could fill in block-until-line-20-exists. Assuming your shell is actually bash; for /bin/sh the loop will be uglier. Commented Apr 29, 2022 at 21:06
  • ...on which point: Do you need POSIX sh compatibility here, or can a shell with ksh extensions (as adopted by both bash and zsh) be assumed? Commented Apr 29, 2022 at 21:08

1 Answer 1

0

Nevermind. I think I answered my own question. tail & sed is the solution after all.

tail -n 0 -f file | sed '20q;d'

Turns out that tail stops blocking after sed completes.

EDIT: depending on how you use this, there is a potential for a time-of-check/time-of-use bug.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.