How do I print multiple sections in a text file?

1

I have a text file looking something like this:

*FILESTART
line_a
line_b
line_c
*INCLUDE
file_A.key
file_B.key
*INCLUDE
file_1.key
file_2.key
file_3.key
*SOMETHING_ELSE
line_x
line_y
line_z
*END

I would like to print only the lines between each *INCLUDE statement and whatever asterisk statement that comes next, in this case the following:

file_A.key
file_B.key
file_1.key
file_2.key
file_3.key

The number of .key files can vary and the names does not always end with .key.

The code for this will be implemented in an existing bash script, so it should be based on awk, sed or something else in "bash style", not Perl, PHP, Python etc.

I have tried things like

sed -n '/^*INCLUDE/,/^\*/p' 

but it only prints the first section and ends by the second *INCLUDE line.

Any suggestions?

user325113

Posted 2014-05-20T09:17:42.487

Reputation: 13

Answers

2

sed does not work in this case because the second *INCLUDE turns of the pattern-range, and it is never turned on again. I think this would be easier with awk, for example you could use a printing flag like this:

awk '/^\*/ { f=0 } /^\*INCLUDE/ { f=1; next } f' file

Output:

file_A.key
file_B.key
file_1.key
file_2.key
file_3.key

Explanation

  • When f==1 the final statement (i.e. the lone f) invokes the default rule {print $0}.
  • f is set to 0 whenever a line starts with an asterisk.
  • f is set to 1 whenever a line starts with *INCLUDE. These lines are also skipped as per the requirement.

Thor

Posted 2014-05-20T09:17:42.487

Reputation: 5 178

That's amazing! Thank you Thor, god of awk. :-) – user325113 – 2014-05-20T10:46:12.463

@Ayodhya. Sorry about that. I'm new here. I've accepted Thor's answer now. Thank you for reminding me. – user325113 – 2014-05-20T11:20:05.083

0

I used a rexx script to do this sort of thing. In essence, you use the script to 'turn on or off echo' based on the presence of *include to *end...

A bit of cleaver programming would allow you to write the output to memory, and run it as a batch file, complete with subroutines and string substitution. This is in effect, the nature of Don Knuth's weave program. You write the documentation and program in the same file, and then extract the program as output.

wendy.krieger

Posted 2014-05-20T09:17:42.487

Reputation: 660