2

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.

1 Answers1

2
$ 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.

Community
  • 1
  • 1
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    You could also invert this and do `sed '/keyword/,$d' file` but I think that is strictly less efficient for this task. – Etan Reisner Apr 15 '15 at 18:37
  • With GNU sed: `sed '/keyword/Q' file` – Cyrus Apr 15 '15 at 18:39
  • @EtanReisner, would you mind explaining why it would be less efficient? – l'L'l Apr 15 '15 at 18:39
  • 1
    @l'L'l The script in the answer needs to match every line against `/keyword/` and as soon as it matches it quits processing the input file and exits. The inversion needs to likewise match every line against `/keyword/` but once it sees it it then continues to read the rest of the file checking whether each line is the last line in the file. So it just processes more data than the original. – Etan Reisner Apr 15 '15 at 18:42
  • 1
    A link to your answer [here](http://stackoverflow.com/a/17914105/258523) might be in order also. I know I marked that question as a favorite to have that ready to hand. – Etan Reisner Apr 15 '15 at 18:55