Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed/Awk: Delete all lines after last occurrence of pattern

Tags:

bash

sed

awk

I have a file with one insert on each line, like below:

INSERT INTO table (columns) values (1,x,b);
INSERT INTO table (columns) values (2,y,c);
INSERT INTO table (columns) values (3,w,d);
INSERT INTO table (columns) values (4,z,e);
-- Comment
SELECT * FROM table;
-- Comment
SELECT * FROM table;

How do I remove every line after the last ocurrence of INSERT INTO? Output I'm looking for is:

INSERT INTO table (columns) values (1,x,b);
INSERT INTO table (columns) values (2,y,c);
INSERT INTO table (columns) values (3,w,d);
INSERT INTO table (columns) values (4,z,e);
like image 425
ganthdev Avatar asked Sep 16 '25 11:09

ganthdev


1 Answers

The easier way is to use tac:

tac file|sed '0,/^INSERT INTO/{/INSERT INTO/!d}'|tac

You can also use awk without tac:

awk 'NR==FNR{if(/^INSERT INTO/)e=NR;next}FNR<=e' file file
like image 66
Kent Avatar answered Sep 18 '25 09:09

Kent