1

I want to delete N lines after a pattern with AWK command.

Input file.txt

bla bla
bla bla
pattern
these lines
are not 
requires
I want to delete 
these...
up to nth line
....
....

Required output file.txt

bla bla
bla bla
pattern

tried solution

awk '/pattern/ {exit} {print}' file.txt

I found this command here but I need the "pattern" as well. Please help!

sai
  • 87
  • 8
  • If you replace the word "pattern" everywhere it occurs in your question with string-or-regexp and full-or-partial then we can really help you, otherwise you will probably get an answer to a different problem than the one you actually have but which produces the expected output from your sample input. See [how-do-i-find-the-text-that-matches-a-pattern](https://stackoverflow.com/questions/65621325/how-do-i-find-the-text-that-matches-a-pattern) – Ed Morton Aug 23 '21 at 14:09
  • You say `I want to delete N lines after` but your code and the answer you accepted delete ALL lines after it, not just N lines. Do you really want to just delete some number of lines or all lines? – Ed Morton Aug 23 '21 at 14:15

4 Answers4

2

A simpler and shorter sed:

sed '/pattern/q' file

bla bla
bla bla
pattern
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

Never use the word "pattern" in the context of matching text as it's highly ambiguous. For example, each of these will produce the expected output from your posted sample input but mean very different things and will behave very differently from each other given different input and the right one for you to use depends on what you mean by "pattern":

Full regexp match:

$ awk '{print} /^pattern$/{exit}' file
bla bla
bla bla
pattern

Partial regexp match:

$ awk '{print} /pattern/{exit}' file
bla bla
bla bla
pattern

Full string match:

$ awk '{print} $0=="pattern"{exit}' file
bla bla
bla bla
pattern

Partial string match:

$ awk '{print} index($0,"pattern"){exit}' file
bla bla
bla bla
pattern

There are other possibilities too depending on whether you want word or line matches. See How do I find the text that matches a pattern?.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1

An awk action can have multiple statements, so something like this should work:

awk '/pattern/ {print; exit} {print}' file.txt
Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
0

You are close, you need just to first print then exit if pattern matched. Let file.txt content be

bla bla
bla bla
pattern
these lines
are not 
requires
I want to delete 
these...
up to nth line
....
....

then

awk '{print}/pattern/{exit}' file.txt

output

bla bla
bla bla
pattern

(tested in GNU Awk 5.0.1)

Daweo
  • 31,313
  • 3
  • 12
  • 25