Stelios
Stelios

Reputation: 1102

Sed copy pattern between range only once

I am using sed to edit some sql script. I want to copy all the lines from the first "CREATE" pattern until the first "ALTER" pattern. The issue I am having is that sed copies all lines between each set of CREATE and ALTER instead of only the first occurrence (more than once).

sed -n -e '/CREATE/,/ALTER/w createTables.sql' $filename

Upvotes: 0

Views: 304

Answers (2)

123
123

Reputation: 11216

Using sed

 sed -n '/CREATE/,/ALTER/{p;/ALTER/q}' file > createTables.sql

or alternatively(note the newline)

sed -n '/CREATE/,/ALTER/{w createTables.sql
/ALTER/q}' file

Upvotes: 2

choroba
choroba

Reputation: 241868

Perl to the rescue:

perl -ne 'print if /CREATE/ .. /ALTER/ && close ARGV' -- "$filename" > createTables.sql

It closes the input when the ALTER is matched, i.e. it doesn't read any further.

Upvotes: 3

Related Questions