Using sed to delete multiple lines below a pattern
I needed to remove a 7-line create statement and two neighboring alter statements from a set of SQL migration files, and I came up with the following sed one-liner:
sed -i '/CREATE.*some_table/,+6d;/ALTER.*some_other_table.*some_column/,+1d' migrations/from*.php
This finds the line "CREATE TABLE 'some_table' (..." and deletes it, plus the 6 lines below it. It also finds the line "ALTER TABLE 'some_other_table' ADD COLUMN 'some_column'..." and deletes it, and the line below it. The trickiest part was figuring out the ,+1 syntax, which says do this for this line and the X number of lines below it. Also note the -i option actually changes the file. If you want to test your sed command, just run sed without -i and examine the output.
Update Note that this syntax is a GNU-only extension, and won't work with all versions of sed


0 Comments
Leave a Comment