Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
    
This shows the basic technique: unix.stackexchange.com/a/22568/4801 –  dubiousjim Apr 19 '12 at 20:05

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
Yeah, sometimes I do the +1 offset with a next, but the -1 would require keeping a buffer. Too bad. –  janmoesen Oct 18 '11 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 Oct 18 '11 at 9:31
    
+1 for knowing ex exists ;-) –  ktf Oct 18 '11 at 9:35
    
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 Oct 18 '11 at 18:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.