Reputation:
Suppose we have a file with the following content:
alpha
beta
keyword
gamma
phi
What is the sed command that looks for the "keyword" pattern match and deletes all lines thereafter? The output would be:
alpha
beta
A similar command, sed -n -e '1,/^keyword/p'
, almost works, but leaves the "keyword" line in the output.
Upvotes: 2
Views: 61
Reputation: 204558
$ sed -n '/keyword/q;p' file
alpha
beta
Some alternatives to consider using a more consistent approach to control what gets printed before/after including/excluding a keyword:
$ awk '/keyword/{f=1} !f' file # = sed -n '/keyword/q;p' file
alpha
beta
$ awk '!f; /keyword/{f=1}' file # = sed -n 'p;/keyword/q' file
alpha
beta
keyword
$ awk '/keyword/{f=1} f' file # = sed -n '/keyword/,$p' file
keyword
gamma
phi
$ awk 'f; /keyword/{f=1}' file # = sed -n '1,/keyword/{d};p' file
gamma
phi
The above awk
scripts consistently just set a flag when keyword is found and you control what gets printed by testing for the flag being set or not before or after the keyword is tested.
The sed
scripts on the other hand have to change style between the 2nd and 3rd versions from a simple test/print to a range expression and introduce different characters/syntax for the 3rd and 4th scripts vs the first 2 scripts.
See also Printing with sed or awk a line following a matching pattern for more solutions to printing a range around a regexp.
Upvotes: 2