sai
sai

Reputation: 87

delete lines after pattern (excluding pattern) using AWK

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!

Upvotes: 1

Views: 1694

Answers (4)

Ed Morton
Ed Morton

Reputation: 203169

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?.

Upvotes: 2

Daweo
Daweo

Reputation: 36360

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)

Upvotes: 0

anubhava
anubhava

Reputation: 784928

A simpler and shorter sed:

sed '/pattern/q' file

bla bla
bla bla
pattern

Upvotes: 2

Wander Nauta
Wander Nauta

Reputation: 19615

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

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

Upvotes: 1

Related Questions