CLI tip 8: extract from start of file until matching line
The GNU sed command has a couple of handy commands to extract text from the start of input until a matching line is found. The q and Q commands are similar, except how they process the matching line.
The q command will exit sed immediately, after printing the current pattern space if applicable.
# quit after a line containing 'st' is found
$ printf 'apple\nsea\neast\ndust' | sed '/st/q'
apple
sea
east
The Q command is similar to q but won't print the matching line.
# matching line won't be printed in this case
$ printf 'apple\nsea\neast\ndust' | sed '/st/Q'
apple
sea
tac+sed+tac will help you get lines starting from the last occurrence of the search string till the end of the input.
$ printf 'apple\nsea\neast\ndust\n' | tac | sed '/ea/q' | tac
east
dust
Be careful if you want to use
qorQcommands with multiple files, assedwill stop even if there are other files left to be processed. You can use mixed address ranges as a workaround. See also unix.stackexchange: applying q to multiple files.
Video demo:
See my CLI text processing with GNU sed ebook if you are interested in learning about the
GNU sed command in more detail.