3

When I want to print lines between two patterns, excluding the lines with those patterns, I can do it in ex using +1 and -1 after the pattern. That is awesome. Is this possible in awk? Right now, I kludge it by setting an is_printing flag.

This is ex to get the column definitions from an SQL table creation:

$ ex schema/media.sql <<< '/^CREATE TABLE/+1,/^)/-1p'
#        id
#                SMALLINT
#                UNSIGNED
#                NOT NULL
#                AUTO_INCREMENT
#                COMMENT 'The auto-generated ID.',
#        parent_id
#                SMALLINT
#                UNSIGNED
#                NULL
#                COMMENT 'The ID of the parent album, if any.',
#        title
#                VARCHAR(255)
#                COLLATE utf8_unicode_ci
#                NOT NULL
#                DEFAULT ''
#                COMMENT 'The album title.',
#        description
#                TEXT
#                COLLATE utf8_unicode_ci
#                NOT NULL
#                COMMENT 'The album''s description.',

This is an awk command to do the same:

$ awk '/^\)/ { exit; } is_printing; /^CREATE TABLE/ { is_printing = 1; }' schema/media.sql

I find the awk version not as readable. Is there an idiom I am missing? Can sed do something like this, too? (I prefer awk's syntax over sed's.)

1

1 Answer 1

1

Sorry, but awk cannot do so, because each line is seperately passed through the script.

Theoretically it would be possible to implement an +x, turning a line match after x more input lines to true, but I don't think I'd like to debug such scripts ;-)

BTW: Although everything may be placed on the same line, I'd vote for a new line at least for every condition/action pair, so scripts are far easier to read and understand.

3
  • Yeah, sometimes I do the +1 offset with a next, but the -1 would require keeping a buffer. Too bad.
    – janmoesen
    Commented Oct 18, 2011 at 9:31
  • 1
    For the record: I completely agree re: readability and can assure you my actual awk scripts are properly formatted. It does underscore the neatness of the ex way for a simple one-liner, though.
    – janmoesen
    Commented Oct 18, 2011 at 9:31
  • I'll leave this open for another day in case someone might come up with a sed way, but given the whopping 18 views so far, I don't think it likely… Thanks for your answer!
    – janmoesen
    Commented Oct 18, 2011 at 18:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .